1-20的阶乘之和(java)

来源:互联网 发布:heavy rotation 知乎 编辑:程序博客网 时间:2024/04/29 15:52

import java.math.BigInteger;

public class Factorial {
 //2) 求1!+2!+……+20!
 public static void main(String[] args){
  BigInteger sum=BigInteger.ZERO;
  for(BigInteger i=BigInteger.ONE;i.intValue()<=20;){
   i=i.add(BigInteger.ONE);
   sum=sum.add(factorial(i));
  }
  System.out.println(sum.toString());
 }

 public static BigInteger factorial(BigInteger bigInteger){
  if(bigInteger.intValue()==1){
   return BigInteger.ONE;
  }
  else
   return bigInteger.multiply(factorial(bigInteger.subtract(BigInteger.ONE)));
 }
}

 

结果:53652269665821260312

 

原创粉丝点击