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

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

问题描述

我是使用Java 8中的Lambda表达式功能的初学者.Lambda表达式在解决诸如素数检查,析因等问题的程序中非常有用。然而,可以使用它们可以有效地用于解决当前值取决于前两个值之和的斐波那契等问题。我已经很好地使用Lambda表达式解决了质数检查问题。

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

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



最简单的解决方案

是使用 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]));

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

  Stream.iterate(new BigInteger [] {BigInteger.ONE,BigInteger.ONE},
p->新的BigInteger [] {p [1],p [0] .add(p [1])})
。的forEach(对GT;的System.out.println(p [0]));

直到您没有足够的内存来表示下一个值为止。



顺便说一句,要从流中获取第n个元素:

$ $ $ $ $ $ $ $> Stream.iterate new long [] {1,1},p - > new long [] {p [1],p [0] + p [1]})
.limit(91).skip(90)。使用FindFirst()得到()[1]。


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.

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

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?

解决方案

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.

BTW, 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天全站免登陆