鉴于我的代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Fact_2 {
public static void main(String args[]) throws IOException {
System.out.println("Please enter a number:");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int fact = Integer.parseInt(input.readLine());
int factorial = 1;
for (int i = 1; i <= fact; i++) {
factorial = factorial * i;
}
System.out.println("The factorial of " + fact + " is " + factorial);
}
}
程序正常工作......最多只能达到第12位。我检查确保所有的阶乘都是正确的,但当你为你的数字输入13时,你得到的是1932053504,它应该是6227020800.为什么会这样?
答案 0 :(得分:4)
我只想添加关于整数溢出的数学推理:
12! = 479,001,600
13! = 6,227,020,800
现在,int
(32位)类型的范围限制为:
-2,147,483,648 to 2,147,483,647
自从因子变为13以来超过了:
479,001,600 < 2,147,483,647 < 6,227,020,800
由于溢出,当你有13阶乘时,它将其视为:
13! = 6,227,020,800 % 4,294,967,296
= 1,932,053,504 + 4,294,967,296 x 1 % 4,294,967,296
= 1,932,053,504
要解决此问题,请使用BigInteger
。如果您不需要它太大,请使用容量为{/ p>的long
–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
long
最多可以处理20!
20! = 2,432,902,008,176,640,000
除此之外,您需要使用BigInteger
答案 1 :(得分:0)
你有溢出...使用BigInteger
类
BigInteger factorial = BigInteger.valueOf(1);
int fact = 13;
for (int i = 1; i <= fact; i++) {
factorial = factorial.multiply(BigInteger.valueOf(i));
}
System.out.println(factorial);