阶乘 For 循环最多只能使用 12

Factorial For Loop only works up to 12

根据我的代码:

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。这是为什么?

你有一个溢出...使用BigInteger class

  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);

我只想添加关于整数溢出的数学推理:

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。如果您不需要它太大,请使用 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