java factorial_Java Longs.factorial(int n)用法及代码示例

Guava LongMath类的factorial(int n)方法返回前n个正整数的乘积,即n!。

用法:

public static long factorial(int n)

参数:该方法仅接受一个整数类型的参数n,用于查找阶乘。

返回值:此方法返回以下值:

如果n为0,则此方法返回1。

如果结果适合长整数,则此方法返回前n个正整数的乘积。

如果结果不适合长时间,则此方法返回Long.MAX_VALUE。

异常:如果n为负数,则factorial(int n)方法将引发IllegalArgumentException。

下面的程序说明LongMath.factorial()方法的使用:

范例1:

// Java code to show implementation of

// factorial(int n) method of Guava's

// LongMath Class

import java.math.RoundingMode;

import com.google.common.math.LongMath;

class GFG {

// Driver code

public static void main(String args[])

{

int n1 = 10;

// Using factorial(int n) method of

// Guava's LongMath class

long ans1 = LongMath.factorial(n1);

System.out.println("factorial of "

+ n1 + " is:"

+ ans1);

int n2 = 12;

// Using factorial(int n) method of

// Guava's LongMath class

long ans2 = LongMath.factorial(n2);

System.out.println("factorial of "

+ n2 + " is:"

+ ans2);

}

}

输出:

factorial of 10 is:3628800

factorial of 12 is:479001600

范例2:

// Java code to show implementation of

// factorial(int n) method of Guava's

// LongMath Class

import java.math.RoundingMode;

import com.google.common.math.LongMath;

class GFG {

static long findFact(int n)

{

try {

// Using factorial(int n) method of

// Guava's LongMath class

// This should throw "IllegalArgumentException"

// as n < 0

long ans = LongMath.factorial(n);

// Return the answer

return ans;

}

catch (Exception e) {

System.out.println(e);

return -1;

}

}

// Driver code

public static void main(String args[])

{

int n = -5;

try {

// Function calling

findFact(n);

}

catch (Exception e) {

System.out.println(e);

}

}

}

输出:

java.lang.IllegalArgumentException:n (-5) must be >= 0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值