我们可以做到:
public static long factorial(long n) {
return (n <= 1) ? 1 : n * factorial(n - 1);
}
public static long twice_factorial(long n) {
return factorial(factorial(n));
}
并且,如果需要,可以通过一些技巧将其变成一个单一的方法:
public static long twice_factorial(long n) {
return new Object() {
long factorial(long n) {
return (n <= 1) ? 1 : n * factorial(n - 1);
}
long twice_factorial(long n) {
return factorial(factorial(n));
}
}.twice_factorial(n);
}
但这是一个无用的函数,因为它只对 n long 类型的限制:
(4!)! = 24! = 620,448,401,733,239,439,360,000
Java 'long' +max = 9,223,372,036,854,755,807
如果您希望此函数有用,您可以改用浮动近似方程。但是在近似值上再次调用近似阶乘可能没有多大意义。您需要嵌套阶乘值本身的浮动近似方程。
或者,我们可以切换到BigInteger:
import java.math.BigInteger;
public class Test {
public static BigInteger factorial(BigInteger n) {
return (n.compareTo(BigInteger.ONE) <= 0) ? n : n.multiply(factorial(n.subtract(BigInteger.ONE)));
}
public static BigInteger twice_factorial(BigInteger n) {
return factorial(factorial(n));
}
public static void main(String[] args) {
System.out.println(twice_factorial(new BigInteger(args[0])));
}
}
用法
> java Test 4
620448401733239439360000
>
但这只能达到 (7!)!在我们得到java.lang.StackOverflowError之前!如果我们想更进一步,我们需要转储递归并迭代计算阶乘:
public static BigInteger factorial(BigInteger n) {
BigInteger result = BigInteger.ONE;
while (n.compareTo(BigInteger.ONE) > 0) {
result = result.multiply(n);
n = n.subtract(BigInteger.ONE);
}
return result;
}
用法
> java Test 8
34343594927610057460299569794488787548168370492599954077788679570543951730
56532019908409885347136320062629610912426681208933917127972031183174941649
96595241192401936325236835841309623900814542199431592985678608274776672087
95121782091782285081003034058936009374494731880192149398389083772042074284
01934242037338152135699611399400041646418675870467025785609383107424869450
...
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000
>