算法设计之Project Euler 02: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.

二、问题描述

Fibonacci数列中的每一项都是由前两项累加得到的,前两项分别为1和2,由此可以得到Fibonacci数列的前10项。

如果一个Fibonacci数列中的所有数都不超过4000000,对这个数列中偶数值的项进行求和。

答案为:4613732

三、第一遍刷Project Euler

思路:将所有的Fibonacci数列保存,然后对其偶数值的项进行求和。

python版本代码:

# 求Fibonacci数列的函数
def Fibonacci(n):
    if (n==1):
        return 1
    elif (n==2):
        return 2
    else:
        return Fibonacci(n-1) + Fibonacci(n-2)


# 对偶数值的项求和
def main(max_num):
    # 找到小于max_num的所有Fibonacci数列
    result = [1,2]
    for i in range(3, max_num):
        result.append(Fibonacci(i))
        if Fibonacci(i) > max_num:
            result.pop(-1)
            break

    # 累加偶数值的项
    count = 0
    for value in result:
        if value%2==0:
            count += values
    print(count)


# 执行程序
if __name__=="__main__":
    main(4000000)

C++版本的代码为:

#include<iostream>

int Fibonacci(int x)
{
	if (x==1)
	{
		return 1;
	}
	else if (x==2)
	{
		return 2;
	}
	else
	{
		return Fibonacci(x - 1) + Fibonacci(x - 2);
	}
}

void main()
{
	int count = 2;
	for (int i = 3; i < 4000000; i++)
	{
		if (Fibonacci(i) > 4000000)
		{
			break;
		}
		else
		{
			if (Fibonacci(i)%2==0)
			{
				count += Fibonacci(i);
			}
		}
	}
	std::cout << count << std::endl;
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/z704630835/article/details/82622782