• 求和: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;  
        }  
    }

  • 相关阅读:
    schema约束和引入
    第一天
    github pages搭建网站(三)
    git安装和使用(二)
    使用github(一)
    命名实体识别总结
    约瑟夫环
    标准化和归一化
    cumsum累计函数系列:pd.cumsum()、pd.cumprod()、pd.cummax()、pd.cummin()
    pandas处理时间序列(4): 移动窗口函数
  • 原文地址:https://www.cnblogs.com/mlan/p/11060354.html
Copyright © 2020-2023  润新知