欧拉计划---0002 Even Fibonacci numbers(四百万以内斐波纳契偶数和)

第二题原文如下:

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, ...

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开始,斐波那契数列的前十项为:

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

考虑斐波那契数列中数值不超过4百万的项,找出这些项中值为偶数的项之和。

python代码:

def SunOfFib():
    x, y, sum = 1, 1, 0
    while x+y < 4000000:
        x, y = y, x+y
        if y % 2 == 0:
            sum += y
    print sum


c代码:

#include <stdio.h>
 
int main()
{
    intx = 1;
    inty = 1;
    intsum = 0;
 
   while (x + y < 4000000)
    {
       int tmp = x;
       x = y;
       y = tmp + x;
       if (y % 2 == 0)
       {
           sum += y;
       }
    }
 
   printf("%d\n", sum);
 
   return 0;
}

c++代码:

#include<iostream>
using namespace std;
 
int main()
{
    int x = 1;
    int y = 1;
    int sum = 0;
 
    while (x + y < 4000000)
    {
        int tmp = x;
        x = y;
        y = tmp + x;
        if (y % 2 == 0)
        {
            sum += y;
        }
    }
 
    cout << sum << endl;
 
    return 0;
}

这上面是我自己写的代码,在网上大家好像都是使用的暴力破解,没有找到相对更好的方法,如果你找到了欢迎贡献学习。


本题的正确答案:4613732


总结:

这个题目是基本题目,锻炼基本语法和基本的思维逻辑。


猜你喜欢

转载自blog.csdn.net/zd199218/article/details/42714081
今日推荐