求和:1 + 1/2! + 1/3! + 1/4! + 1/5! + ... + 1/50!

package com.jnwork;

public class SquenceTest {
	 /** 
     * 求和:1 + 1/2! + 1/3! + 1/4! + 1/5! + ... + 1/50! 
     * @param args 
     */  
    public static void main(String[] args) {  
        System.out.println("递归求和:" + SquenceTest.getSquenceSum(50));  
        System.out.println("迭代求和:" + getSequenceSumByInterator(50));  
    }  
      
    /** 
     * 递归求和 
     * @param n 
     * @return 
     */  
    public static double getSquenceSum(int n) {  
        long startTime = System.currentTimeMillis();  
        if(n == 1) {  
            return 1d;  
        }  
        double sum = 1d;  
        double a = 1d;  
        for(int i = 2; i <= n; i++) {  
            long num = getSquenceValueByRecurvise(i);  
            sum += a / num;  
        }  
        System.out.println("递归求和耗时:" + (System.currentTimeMillis() - startTime) + "ms");//0ms  
        return sum;  
    }  
      
    /** 
     * 递归方式 
     * @param n 
     * @return 
     */  
    public static long getSquenceValueByRecurvise(int n) {  
        if(n == 1) {  
            return 1;  
        }  
        long squenceValue = n * getSquenceValueByRecurvise(n-1);  
        return squenceValue;  
    }  
      
    /** 
     * 迭代求和 
     */  
    public static double getSequenceSumByInterator(int n) {  
        long startTime = System.currentTimeMillis();  
        if(n == 1) {  
            return 1d;  
        }  
        double sum = 1d;  
        double a = 1d;  
        long beforeSeqValue = 1;  
        long nextSeqValue = 0;  
        for(int i = 2; i <= n; i++  ) {  
            //迭代关系(an = n * a(n-1) an-1 = an;)  
            nextSeqValue = i * beforeSeqValue;//相当于数学中的递推公式  
            beforeSeqValue = nextSeqValue;  
            sum += a / nextSeqValue;  
        }  
        /*while(n > 1) { 
            nextSeqValue = n * beforeSeqValue; 
            beforeSeqValue = nextSeqValue; 
            n--; 
        }*/  
        System.out.println("迭代求和耗时:" + (System.currentTimeMillis() - startTime) + "ms");//0ms  
        return sum;  
    }  
}

原文地址:https://www.cnblogs.com/mlan/p/11060354.html