Java 8 Lambda expressions for solving fibonacci (non recursive way)
The simplest solution is to use a stream of Pair
s:
Stream.iterate(new long[] { 1, 1 }, p -> new long[] { p[1], p[0] + p[1] })
.limit(92)
.forEach(p -> System.out.println(p[0]));
Due to the lack of a standard pair type, it uses a two-element array. Further, I use .limit(92)
as we can't evaluate more elements using long
values. But it's easy to adapt to BigInteger
:
Stream.iterate(new BigInteger[] { BigInteger.ONE, BigInteger.ONE },
p -> new BigInteger[] { p[1], p[0].add(p[1]) })
.forEach(p -> System.out.println(p[0]));
That'll run until you haven't enough memory to represent the next value.
By the way, to get the nth element from the stream:
Stream.iterate(new long[] { 1, 1 }, p -> new long[] { p[1], p[0] + p[1] })
.limit(91)
.skip(90)
.findFirst()
.get()[1];
To get the Nth fibonacci element (using reduction):
Stream.iterate(new long[] {1, 1}, f -> new long[] { f[1], f[0] + f[1] })
.limit(n)
.reduce((a, b) -> b)
.get()[0];
Here is what is going on:
-
Stream::iterate
- is producing pairs of numbers, each containing two consecutive elements of fibonacci. We have to use pairs, because we can access only the last element via "iterate", not two or more previous elements, so to generate a new pair, we get the last pair, which already contains two previous elements of fibonacci, and produce the next pair. And to get the Nth fibonacci element, we just need to get the left value from the Nth pair. -
.limit(n)
- to keep the first N pairs, and exclude the rest. -
.reduce((a, b) -> b)
- to get the last pair from the stream of N pairs from previous step. -
.get()[0]
- extract fibonacci element from the pair (left value of the pair)