Pan*_*s K 5 java biginteger java-stream
您好,我目前有这段代码用于查找工作正常的阶乘
public static BigInteger factorial(BigInteger n) {
BigInteger sum = BigInteger.ONE;
for (BigInteger i = BigInteger.ONE; i.compareTo(n) <= 0; i = i.add(BigInteger.ONE)) {
sum = sum.multiply(i);
}
return sum;
}
Run Code Online (Sandbox Code Playgroud)
我想要实现的是将其转换为 aStream<BigInteger>
并像这样写
public static BigInteger factorial(BigInteger n) {
return getBigIntegerStream(n).reduce(BigInteger.ONE, BigInteger::multiply);
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是如何获得Stream<BigInteger>
类似于如何声明IntStream
?
IntStream.range(1, myInt);
Run Code Online (Sandbox Code Playgroud)
也许是这样的:
public static BigInteger factorial(BigInteger n) {
return Stream.iterate (BigInteger.ONE, i -> i.add(BigInteger.ONE)).limit(Integer.parseInt(n.toString())).reduce(BigInteger.ONE, BigInteger::multiply);
}
Run Code Online (Sandbox Code Playgroud)
编辑:我忘记限制流了。现在修好了。
int
当然,只接受一个(或一个long
)作为参数会更简单:
public static BigInteger factorial(int n) {
return Stream.iterate (BigInteger.ONE, i -> i.add(BigInteger.ONE)).limit(n).reduce(BigInteger.ONE, BigInteger::multiply);
}
Run Code Online (Sandbox Code Playgroud)
您甚至不太可能需要计算大于 的数字的阶乘Integer.MAX_VALUE
。这样一个数字的阶乘将会很大,并且可能需要很长时间才能计算。
编辑:不是一个合适的基准,但factorial(100000)
花了我 5 秒,factorial(1000000)
花了 8 分钟。按照这个速度,factorial(Long.MAX_VALUE)
甚至factorial(Integer.MAX_VAULE)
会需要非常非常长的时间。因此我不认为需要争论的意义BigInteger
。