Skip to content

Latest commit

 

History

History
109 lines (75 loc) · 2.83 KB

File metadata and controls

109 lines (75 loc) · 2.83 KB

Java 程序:查找数字的阶乘

原文: https://www.programiz.com/java-programming/examples/factorial

在此程序中,您将学习使用 Java 中的forwhile循环查找数字的阶乘。

正数n的阶乘由下式给出:

factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n

示例 1:使用for循环查找数字的阶乘

public class Factorial {

    public static void main(String[] args) {

        int num = 10;
        long factorial = 1;
        for(int i = 1; i <= num; ++i)
        {
            // factorial = factorial * i;
            factorial *= i;
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}

运行该程序时,输出为:

Factorial of 10 = 3628800

在此程序中,我们使用循环来循环遍历 1 至给定数字num(10)之间的所有数字,并将每个数字的乘积存储在变量factorial,直到i <= num

我们使用了long而不是int来存储较大的阶乘结果。 但是,它仍然不足以存储较大数字(例如 100)的值。

对于不能存储在长变量中的结果,我们使用在java.math库中声明的BigInteger变量。

示例 2:使用BigInteger查找数字的阶乘

import java.math.BigInteger;

public class Factorial {

    public static void main(String[] args) {

        int num = 30;
        BigInteger factorial = BigInteger.ONE;
        for(int i = 1; i <= num; ++i)
        {
            // factorial = factorial * i;
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}

运行该程序时,输出为:

Factorial of 30 = 265252859812191058636308480000000

在这里,我们使用BigInteger变量阶乘代替long

由于*不能与BigInteger一起使用,因此我们将multiply()用于产品。 同样,应将number强制转换为BigInteger以进行乘法。


同样,我们也可以使用while循环来解决此问题。

示例 3:使用while循环查找数字的阶乘

public class Factorial {

    public static void main(String[] args) {

        int num = 5, i = 1;
        long factorial = 1;
        while(i <= num)
        {
            factorial *= i;
            i++;
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}

运行该程序时,输出为:

Factorial of 5 = 120

在上面的程序中,与for循环不同,我们必须在循环体内增加i的值。

尽管两个程序在技术上都是正确的,但在这种情况下最好使用for循环。 这是因为迭代次数(最多num)是已知的。

访问此页面以学习使用递归查找数字的阶乘。