【java】计算N的阶乘

来源:互联网 发布:从律所跳槽当法务知乎 编辑:程序博客网 时间:2024/05/19 13:25
public BigInteger Nstate(int n) {        // long result=1;      /* for(int i=1;i<n;i++){         result*=n;       }        return result;*/        BigInteger result = new BigInteger("1");//超过30!应该使用BigInteger        for (int i = 1; i <= n; i++) {            BigInteger num = new BigInteger(String.valueOf(i));            result = result.multiply(num);// 调用自乘方法        }        return result;    }

 

上面的代码 如果n>=30 也可以算出正确的结果,如果用注释那段代码就会有问题 当然30还不会有问题 因为没超过long的范围,但是阶乘这种东西很容易超过范围的比如你n=300,long也承载不下了,因此这时候我用java提供的类 BigInteger 调用他的自乘方法multiply(num)

0 0
原创粉丝点击