50000的阶乘

50000的阶乘,最开始我是用递归实现的,代码如下:

/**

* 递归实现求阶乘

* @param n

* @return

*/

public static BigInteger getResult(long n) {

if (n==1) {

return BigInteger.valueOf(1);

}

else {

return getResult(n-1).multiply(BigInteger.valueOf(n-1));

}

}

写好后随便输了个数(10,20)试了下,没问题,后来试了下5000,也没问题,再改成10000,结果就报错了,java.lang.StackOverflowError,堆栈溢出!网上查了下,原来是递归的层次太多了,看来递归也不是什么特别特别号的方法哈,当然他也有他自己的好处,那不行啊,得改成循环,就又写了个循环的方法:

/**

* 循环实现求n的阶乘

* @param n

* @return

*/

public static BigInteger xunHuan(long n) {

BigInteger cBigInteger=BigInteger.valueOf(1);

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

cBigInteger=cBigInteger.multiply(BigInteger.valueOf(i));

}

return cBigInteger;

}

嗯,这个求10000的阶乘是没问题了,但是还是有问题啊,50000这数字太大了,算起来要好长时间的,40多秒,就又想了个办法,把它分成两次计算,然后这两部分相乘,

public static BigInteger getAnothor(long begin,long end) {

BigInteger cBigInteger=BigInteger.valueOf(1);

for (long i = begin; i < end; i++) {

cBigInteger=cBigInteger.multiply(BigInteger.valueOf(i));

}

return cBigInteger;

}




BigInteger anothor = getAnothor(1, 50000);
text.setText(""+anothor);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值