1. 引言
实现阶乘的方法很多,这边介绍三种方法,分别是递归,尾递归,循环和BigDecimal。
2. 代码
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Alogrithm a = new Alogrithm1();
a.fact(5);
a.print(a.factN(6));
a.print(a.factFor(7));
}
}
class Alogrithm{
void fact(int n){
fact_inter(n,1);
}
int fact_inter(int n, int product){
if(n == 1 || n == 0){
System.out.println("step n=" + n +" value:"+product);
return 1*product;
}else{
System.out.println("step n=" + n +" value:"+product);
return fact_inter((n-1),n*product);
}
}
int factN(int n){
if(n == 1 || n==0){
return 1;
}else{
return n*factN(n - 1);
}
}
int factFor(int n){
int sum = 1;
if(n == 0){
return 1;
}
for(int i = 1; i <= n; i++){
sum*=i;
}
return sum;
}
void print(int x){
System.out.println("x=" + x);
}
}
3. 输出
step n=5 value:1
step n=4 value:5
step n=3 value:20
step n=2 value:60
step n=1 value:120
x=720
x=5040
4. 说明
int类型的输出 n只能支持到12,在12-33的数值会得到错误的输出值可能正数可能负数,34及以上输出0.
long类型的输出 n只能支持到20,在20-65的数值会得到错误的输出值可能正数可能负数,36及以上输出0.
5.牛逼的BigDecimal来了
修改下上面的部分代码如下:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Alogrithm a = new Alogrithm1();
a.fact(5);
a.print(a.factN(6));
a.print(a.factFor(7));
a.print(a.factBig(100));
a.print(a.factBig(1000));
}
}
//BigDecimal的递归方法,其它两种方式把int替换成BigDecimal处理也等价
public BigDecimal factBig(int n){
if(n == 1 || n==0){
return BigDecimal.valueOf(1);
}else{
return BigDecimal.valueOf(n).multiply(factBig(n - 1));
}
}
//修改输出
void print(Object x){
System.out.println("x=" + x.toString());
}
这样子n的值就可以很大了,不受int和long的长度限制了。