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
踩
分享到:
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,还望指教