java factorial_[Java]函数求阶乘n!(factorial)(四种方法)

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的长度限制了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值