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

本文介绍了一种使用递归和迭代方法计算特定数列和的Java实现。该数列为1+1/2!+1/3!+...+1/50!,通过两种不同算法对比展示了递归和迭代在实际应用中的效率差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;  
    }  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值