題目2:在斐波那契數列中,找出4百萬以下的項中值爲偶數的項之和。

斐波那契數列中的每一項被定義爲前兩項之和。從1和2開始,斐波那契數列的前十項爲:

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

考慮斐波那契數列中數值不超過4百萬的項,找出這些項中值爲偶數的項之和。

 

原題目鏈接:Problem 2


也沒什麼好說的,暴力算


public class Problem2 {

    //answer: 4613732
    public static void main(String[] args) {

        int sum = 0;

        int sum_even = 0;

        int a = 1;
        int b = 2;

        Boolean flag = true;
        while(flag){
            sum = a + b;
            a = b;
            b = sum;
            if(b >= 4000000)
                flag = false;

            if(a % 2 == 0)
                sum_even += a;

        }

        System.out.println(sum_even);

    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章