Java calculates the sum of 1-N factorials

From , 3 Years ago, written in Java, viewed 53 times.
URL https://pastebin.vip/view/530ad673
  1. import java.math.BigInteger;  
  2.  
  3. public class Test02{  
  4.      
  5.     /**
  6.      * 计算从1到n个数的阶乘的总和
  7.      * @param s
  8.      * @return
  9.      */  
  10.     public static BigInteger summation(int n){  
  11.         BigInteger sum = new BigInteger("0");  
  12.         if(n <= 1) return BigInteger.ONE;    //因0!= 1  所以 n <= 1 时返回 1  
  13.         for(int i=1; i<=n; i++){          
  14.             sum = sum.add(factorial(i));  
  15.         }  
  16.         return sum;  
  17.     }  
  18.     /**
  19.      * (递归)计算 n 的阶乘
  20.      * @param n
  21.      * @return sum
  22.      */  
  23.     public static BigInteger factorial(int n){        
  24.         if(n > 0){            
  25.             return BigInteger.valueOf(n).multiply(factorial(n-1));  
  26.         }else{      //因0!= 1   所以 n <= 1 时返回 1  
  27.             return BigInteger.ONE;  
  28.         }  
  29.     }  
  30.     public static void main(String[] args){  
  31.         for(int i=1; i<=30; i++){  
  32.             System.out.println(i + " 的阶乘 = " + factorial(i));  
  33.         }  
  34.         for(int i=1; i<=30; i++){  
  35.             System.out.println("从1到" + i + "的阶乘的总和  = " + summation(i));  
  36.         }                
  37.     }  
  38. }
  39.  
  40.  
  41. //java/7035

Reply to "Java calculates the sum of 1-N factorials"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website