我在Java8和lambda表达式以及Stream中相对较新,我可以使用for循环或递归计算阶乘。但是,是否有一种方法可以使用IntStream计算一个数字的阶乘?即使是整数范围内的阶乘,我也很好。
我在这里阅读了IntStream文档,http://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html和我可以看到这么多的方法,但不确定哪种方法可以用来计算阶乘。
例如,有一个rang方法说,
range(int startInclusive,int endExclusive)通过增量步骤1将顺序有序的IntStream从startInclusive (包含)返回到endExclusive (独占)。
因此,我可以使用它向IntStream提供要乘以的数字范围来计算阶乘。
number = 5;
IntStream.range(1, number)但是如何把这些数字乘以得到阶乘呢?
发布于 2015-02-12 18:01:43
你可以用IntStream::减少来做这个工作,
int number = 5;
IntStream.rangeClosed(2, number).reduce(1, (x, y) -> x * y)发布于 2015-02-12 18:17:03
要获得所有无限阶乘的流,您可以这样做:
class Pair{
final int num;
final int value;
Pair(int num, int value) {
this.num = num;
this.value = value;
}
}
Stream<Pair> allFactorials = Stream.iterate(new Pair(1,1),
x -> new Pair(x.num+1, x.value * (x.num+1)));allFactorials是从1开始到.若要获得1到10的阶乘,请执行以下操作:
allFactorials.limit(10).forEach(x -> System.out.print(x.value+", "));打印: 1,2,6,24,120,720,5040,40320,362880,3628800,
现在假设您只希望有一个特定数字的阶乘,那么就这样做:
allFactorials.limit(number).reduce((previous, current) -> current).get()最棒的是,你不再为新的数字重新计算,而是建立在历史的基础上。
发布于 2017-11-13 19:51:31
使用LongStream.range(),您可以计算数字小于20的阶乘。如果需要计算较大的数字,请使用BigInteger创建流:
public BigInteger factorial(int number) {
if (number < 20) {
return BigInteger.valueOf(
LongStream.range(1, number + 1).reduce((previous, current) -> previous * current).getAsLong()
);
} else {
BigInteger result = factorial(19);
return result.multiply(Stream.iterate(BigInteger.valueOf(20), i -> i.add(BigInteger.ONE)).limit(number - 19)
.reduce((previous, current) -> previous.multiply(current)).get()
);
}
}https://stackoverflow.com/questions/28484544
复制相似问题