用于求解斐波那契的 Java 8 Lambda 表达式(非递归方式) [英] Java 8 Lambda expressions for solving fibonacci (non recursive way)

查看:16
本文介绍了用于求解斐波那契的 Java 8 Lambda 表达式(非递归方式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是在 Java 8 中使用 Lambda 表达式功能的初学者.Lambda 表达式在解决诸如质数检查、阶乘等程序时非常有用.

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.

然而,它们能否有效地用于解决像斐波那契这样的问题,其中当前值取决于前两个值的总和.我已经很好地使用 Lambda 表达式有效地解决了素数检查问题.下面给出了相同的代码.

However can they be utilized effectively in solving problems like Fibonacci where the current value depends on sum of previous two values. I have pretty well solved prime number check problem effectively using Lambda expressions. The code for the same is given below.

boolean checkPrime=n>1 && LongStream.range(2, (long) Math.sqrt(n)).parallel().noneMatch(e->(n)%e==0);

在上述 noneMatch 方法的代码中,我们使用范围内的当前值 (e) 进行评估.但是对于斐波那契问题,我们需要前两个值.

In the above code in the noneMatch method we are evaluating with the current value(e) in the range. But for the Fibonacci problem, we requires previous two values.

我们怎样才能做到这一点?

How can we make it happen?

推荐答案

最简单的解决方案是使用 Pair 的流:

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

由于缺少标准的pair类型,它使用了一个二元数组.此外,我使用 .limit(92) 因为我们无法使用 long 值评估更多元素.但是很容易适应BigInteger:

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.

顺便说一下,从流中获取n个元素:

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

这篇关于用于求解斐波那契的 Java 8 Lambda 表达式(非递归方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆