📌  相关文章
📜  Java番石榴 |带有示例的 Longs.factorial(int n) 方法(1)

📅  最后修改于: 2023-12-03 14:43:02.037000             🧑  作者: Mango

Java番石榴 | 带有示例的 Longs.factorial(int n) 方法

在Java编程语言中,经常需要计算数学中的阶乘。而Guava中的Longs类中提供了一个阶乘方法factorial(int n),它可以计算非常大的数的阶乘,返回一个long类型的结果。在本篇文章中,我们将详细介绍Longs.factorial(int n)方法的使用方法,并提供示例代码。

Longs.factorial(int n)方法

Longs.factorial(int n)方法用于计算n的阶乘,并返回一个long类型的结果。如果n为负数,则会抛出IllegalArgumentException异常。如果n为正数但大于20,则会抛出ArithmeticException异常,因为long类型无法容纳大于20的阶乘结果。

该方法的声明如下:

public static long factorial(int n)
示例代码

下面是一个简单的示例代码,展示了如何使用Longs.factorial(int n)方法来计算一个数的阶乘。我们将测试3的阶乘和21的阶乘。

import com.google.common.primitives.Longs;

public class FactorialExample {

    public static void main(String[] args) {
        int n1 = 3;
        int n2 = 21;

        long result1 = Longs.factorial(n1);
        long result2 = Longs.factorial(n2);

        System.out.println(n1 + "! = " + result1);
        System.out.println(n2 + "! = " + result2);
    }
}

输出结果为:

3! = 6
Exception in thread "main" java.lang.ArithmeticException: Overflow
	at com.google.common.math.LongMath.checkedMultiply(LongMath.java:956)
	at com.google.common.math.LongMath.factorial(LongMath.java:429)
	at com.google.common.primitives.Longs.factorial(Longs.java:338)
	at FactorialExample.main(FactorialExample.java:12)

可以看出,当输入的数值大于20时,方法抛出了ArithmeticException异常。如果继续计算更大的数值的阶乘,则需要使用BigInteger类。

总结

在本篇文章中,我们详细介绍了Guava中Longs类的factorial(int n)方法,展示了如何使用该方法计算一个数的阶乘。当输入的数值太大时,方法会抛出异常。在实际编程中,要根据具体的需求来选择合适的数据类型。