计算函数式Java中的阶乘递归

问题描述 投票:3回答:2

我尝试以函数形式计算阶乘。

我这样做:

 private static Function<BigInteger, BigInteger> factorial = x -> BigInteger.ONE.equals(x)
        ? BigInteger.ONE
        : x.multiply(Main.factorial.apply(x.subtract(BigInteger.ONE)));

而且我尝试获得StackOverflowError时也得到了11111。>

但是当我使用这种方法计算阶乘时:

private static BigInteger factorial(BigInteger request) {
    if (BigInteger.ONE.equals(request)) return BigInteger.ONE;
    else return request.multiply(factorial(request.subtract(BigInteger.ONE)));
}

我不用StackOverflowError就可以得到结果。

功能样式效果较差吗?为什么?

我尝试以功能样式计算阶乘。我这样做了:private static Function factorial = x-> BigInteger.ONE.equals(x)? BigInteger.ONE:...

java lambda functional-programming
2个回答
0
投票

您的术语有些混乱。您显示的示例中的Both


0
投票

功能调用的数量是功能调用的两倍。见图片。

© www.soinside.com 2019 - 2024. All rights reserved.