且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 8中记忆的无限Fibonacci序列

更新时间:2022-02-06 23:41:02

您可以使用基于地图的memoized fibonacci(x)并从中创建无限流:

You can take your map-based memoized fibonacci(x) and make an infinite stream out of it like this:

LongStream fibs = IntStream.iterate(1, i->i+1).mapToLong(i -> fibonacci(i));

但是,制作无限的斐波纳契数字流的最简单方法是这样的:

But the easiest way to make an infinite stream of fibonacci numbers is like this:

LongStream fibs = Stream.iterate(
        new long[]{1, 1},
        f -> new long[]{f[1], f[0] + f[1]}
).mapToLong(f -> f[0]);

正如您所链接的文章指出的那样,无限实际上意味着直到长时间溢出很快。如果你想生成数百个斐波纳契数,请用BigInteger代替long:

As the article you linked to points out, "infinite" really means "until long overflows" which happens quickly. If you want to generate hundreds of fibonacci numbers, replace long with BigInteger:

    Stream<BigInteger> bigFibs = Stream.iterate(
            new BigInteger[]{BigInteger.ONE, BigInteger.ONE},
            f -> new BigInteger[]{f[1], f[0].add(f[1])}
    ).map(f -> f[0]);