阶乘java_Java中求阶乘的算法

本文介绍了三种在Java中计算阶乘的方法:一般算法、递归算法和使用BigInteger。通过示例代码展示了每种方法的实现,并指出递归算法可能因整数溢出导致错误,而使用BigInteger可以处理大整数的阶乘计算。最后,文章中包含了一条关于代码错误的用户评论。
摘要由CSDN通过智能技术生成

Java中求阶乘的算法

1.一般算法:

public class Factorial {

public static int factorial(int n) {

if (n < 0 || n > 16) {

System.err.println("n must be great than 0 and less than 17");

return -1;

} else if (n == 0) {

return 1;

} else {

int result = 1;

for (int i = 1; i <= n; i++) {

result *= i;

}

return result;

}

}

public static void main(String args[]) {

System.out.println("result = " + factorial(5));

}

}

运行结果:result = 120

2.递归算法:

public class Factorial {

public static int recursion(int n) {

if (n < 0 || n > 16) {

System.err.println("n must be great than 0 and less than 17");

return -1;

} else if (n == 0) {

return 1;

} else {

return n * recursion(n - 1);

}

}

public static void main(String[] args) {

System.out.println("result = " + recursion(16));

}

}

运行结果:result = 2004189184

3.使用BigInteger

import java.math.BigInteger;

public class Factorial {

public static BigInteger bigInteger(int n) {

BigInteger result = new BigInteger("1");

if (n < 0) {

System.err.println("n must be great than 0");

return new BigInteger("-1");

} else if (n == 0) {

return new BigInteger("1");

} else {

for (int i = 1; i <= n; i++) {

BigInteger num = new BigInteger(String.valueOf(i));

result = result.multiply(num);

}

return result;

}

}

public static void main(String[] args) {

System.out.println("result = " + bigInteger(100));

}

}

运行结果:result = 93326215443944152681699238856266700490715968264381621468592963895

217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

1

0

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2011-04-08 13:38

浏览 6604

评论

2 楼

clausewitzer

2011-10-28

郭鹏恩 写道

第二种求n的阶乘好像不对啊,但是我找不到毛病出在哪了,12的阶乘能对,到了13就出错了,13的阶乘是6 227 020 800,而用这个程序则是1932053504,还望指教

好像是超出int型的最大范围(65536)了

1 楼

郭鹏恩

2011-10-22

第二种求n的阶乘好像不对啊,但是我找不到毛病出在哪了,12的阶乘能对,到了13就出错了,13的阶乘是6 227 020 800,而用这个程序则是1932053504,还望指教

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值