Java 8 Lambda expressions for solving fibonacci (non recursive way)

后端 未结 6 1144
广开言路
广开言路 2020-12-03 07:27

I am a beginner in using Lambda expression feature in Java 8. Lambda expressions are pretty well useful in solving programs like Prime number check, factorial etc.

H

6条回答
  •  一生所求
    2020-12-03 08:00

    The simplest solution is to use a stream of Pairs:

    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];
    

提交回复
热议问题