Problem 002

欧拉计划----https://projecteuler.net/


偶斐波那契数

斐波那契数列中的每一项都是前两项的和。由1和2开始生成的斐波那契数列前10项为:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

考虑该斐波那契数列中不超过四百万的项,求其中为偶数的项之和。

public class Problem2 {

    static long cal(long num) {
        long s=0;
        long theBeforeNum=1;
        long theAfterNum=2;
        long temp=0;
        while (theAfterNum<num) {
            if(theAfterNum%2==0) {
                s+=theAfterNum;
            }
            temp=theAfterNum;
            theAfterNum=theBeforeNum+theAfterNum;
            theBeforeNum=temp;
        }
        return s;
    }
    

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        System.out.println(cal(4000000));
        long end = System.currentTimeMillis();
        System.out.println("runtime:" + (end - start));
    }

}

 

posted @ 2018-02-06 10:50  Alice-CC  阅读(108)  评论(0编辑  收藏  举报