你可以从别人那里汲取某些思想,但必须|

ChrisNg

园龄:4年4个月粉丝:6关注:4

欧拉计划002--偶斐波那契数

欧拉计划002--偶斐波那契数

首先看一下题目

Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with \(1\) and \(2\), the first \(10\) terms will be:

\[1,2,3,5,8,13,21,34,55,89,\cdots \]

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

偶斐波那契数

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

\[1,2,3,5,8,13,21,34,55,89,\cdots \]

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

解题思路:

其实这一道题,就是单纯的遍历一次,并没有取巧的方法。退出循环的条件条件就是Fibonacci[i] > 4000000。判断是否为偶数的方法就是如果i%2==0成立,那么i就为偶数。

#include <iostream>
using namespace std;
long long Fibonacci[1000] = {1, 2};
long long sum = 2;
int main() {
    for (int i = 3; ; i ++) {
        Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];
        if (Fibonacci[i] > 4000000) 
            break;
        if (Fibonacci[i] % 2 == 0) 
            sum += Fibonacci[i];
    }
    cout << sum << endl;
    return 0;
}

最后算出来的结果为7049156。

本文作者:ChrisNg

本文链接:https://www.cnblogs.com/chrisng/p/15312251.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   ChrisNg  阅读(135)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起