题解 | #计算200以内正整数的阶乘#
计算200以内正整数的阶乘
http://www.nowcoder.com/questionTerminal/155abf9586be4274a55455c9e721619e
提供一种新思路:递归优化+BigInteger的使用
- 将阶乘的逻辑简化为
单例解释:
1 * 2 * 3
x * y
z = x * y = 1 * 2 = 2;
此时让x保存z(已计算)的值,并且让y向后移动一位
x = z
y ++
此时x = 2为2!的最终值,让它与下一轮的值3(y++)计算得到3!
- Java代码实现
import java.util.*;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n < 1 || n > 200)
System.out.println("Error");
System.out.println(solution(n));
}
public static BigInteger solution(int n) {
BigInteger x = BigInteger.valueOf(1);
BigInteger y = BigInteger.valueOf(2);
BigInteger z = BigInteger.ZERO;
for(int i = 1; i < n ; i ++) {
z = x.multiply(y);
x = z;
y = y.add(BigInteger.valueOf(1));
}
return x;
}
}