java 计算阶乘的四个例子代码
public class Factorial {
public static int factorial(int x) {
if (x < 0) {
throw new IllegalArgumentException("x must be>=0");
}
int fact = 1;
for (int i = 2; i <= x; i ) {
fact *= i;
}
return fact;
}
public static void main(String args[]) {
System.out.print(factorial(10));
}
}
这个是利用递归算法制成的。
<table style="border-right: #cccccc 1px dotted; table-layout: fixed; border-top: #cccccc 1px dotted; border-left: #cccccc 1px dotted; border-bottom: #cccccc 1px dotted" cellspacing="0" cellpadding="6" width="95%" align="center" border="0"> <tbody> <tr> <td style="word-wrap: break-word" bgcolor="#f3f3f3">
public class factorial2 {
public static int factorial2(int x) {
if (x < 0) {
throw new IllegalArgumentException("x must be>=0");
}
if (x <= 1) {
return 1;
} else
return x * factorial2(x - 1);
}
public static void main(String args[]) {
System.out.print(factorial2(10));
}
}</td> </tr> </tbody> </table>
这个是数组添加的方法制成的,可以计算更大的阶乘。
<table style="border-right: #cccccc 1px dotted; table-layout: fixed; border-top: #cccccc 1px dotted; border-left: #cccccc 1px dotted; border-bottom: #cccccc 1px dotted" cellspacing="0" cellpadding="6" width="95%" align="center" border="0"> <tbody> <tr> <td style="word-wrap: break-word" bgcolor="#f3f3f3">
public class Factorial3 {
static long[] table = new long[21];
static {table[0] = 1; }
static int last = 0;
public static long factorial(int x) throws IllegalArgumentException {
if (x >= table.length) {
throw new IllegalArgumentException("Overflow; x is too large.");
}
if (x <= 0) {
throw new IllegalArgumentException("x must be non-negative.");
}
while (last < x) {
table[last 1] = table[last] * (last 1);
last ;
}
return table[x];
}
public static void main(String[] args) {
System.out.print(factorial(17));
}
}</td> </tr> </tbody> </table>
最后一个是利用BigInteger类制成的,这里可以用更大的更大的阶乘。
<table style="border-right: #cccccc 1px dotted; table-layout: fixed; border-top: #cccccc 1px dotted; border-left: #cccccc 1px dotted; border-bottom: #cccccc 1px dotted" cellspacing="0" cellpadding="6" width="95%" align="center" border="0"> <tbody> <tr> <td style="word-wrap: break-word" bgcolor="#f3f3f3">
import java.math.BigInteger;
import java.util.*;
public class Factorial4{
protected static ArrayList table = new ArrayList();
static{ table.add(BigInteger.valueOf(1));}
public static synchronized BigInteger factorial(int x){
for(int size=table.size();size<=x;size ){
BigInteger lastfact= (BigInteger)table.get(size-1);
BigInteger nextfact= lastfact.multiply(BigInteger.valueOf(size));
table.add(nextfact);
}
return (BigInteger) table.get(x);
}
public static void main(String[] args) {
System.out.print(factorial(17));
}
}</td> </tr> </tbody> </table>
您可能感兴趣的文章:
python阶乘怎么写
php递归函数求阶乘
阶乘python怎么打
java 计算阶乘的四个例子代码
python递归求阶乘的方法
一文了解Python中的递归
python求n的阶乘
javascript 赋值运算符
Python函数的高级用法
PHP计算身份证校验码示例