有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。

package com.haowu.testHashEquels;


public class BrokerTest {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        //采用递归方法求值
        getsum(50);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        long start2 = System.currentTimeMillis();
        //采用简单的for循环
        getsumab(50);
        long end2 = System.currentTimeMillis();
        System.out.println(end2 - start2);
    }

    public static void getsum (int n){
        float sum = 0;
        for (int i = 1; i <= n; i++) {
            float a = geta(i);
            float b = getb(i);
            sum+=(a/b);
        }
        System.out.println(sum);

    }

    /**递归方式求分子*/
    public static float geta(int n){
        if(n==1){
            return 2;
        }
        if(n==2){
            return 3;
        }

        return geta(n-2) +geta(n-1);
    }

    /**递归方式求分母*/
    public static float getb(int n){
        if(n==1){
            return 1;
        }
        if(n==2){
            return 2;
        }
        return getb(n-2) +getb(n-1);
    }

    /**直接循环方式求值*/
    public static void getsumab(int n){
        float a = 1;
        float b = 2;
        float sum = 0;
        for (int i = 1; i <= n ; i++) {
            sum += (b/a);
            float t = a;
            a=b;
            b=a+t;
        }
        System.out.println(sum);



    }



}

当求前50项的和时分别耗时如下:
递归方式求前50项之和为:81.201294
递归方式求前50项耗时为:187884ms
采用普通循环方式求前50项之和为:81.201294
采用普通循环方式求前50项耗时为:0ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值