projecteuler第二题

Posted 郭新晨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了projecteuler第二题相关的知识,希望对你有一定的参考价值。

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.

 

这个问题是求小于4百万的fibonacci序列中的偶数的和

第一个思路:构造数列,累加其中的偶数

vector<int> data;
data.push_back(1);
data.push_back(2);
int cur_index = 2;

int sum = 2;
while(true)
{
int cur_num = data[cur_index-1]+data[cur_index-2];
if(cur_num>4000000)
{
break;
}
data.push_back(cur_num);
if(cur_num%2==0)
{
sum+= cur_num;
}
cur_index++;


}

cout<<sum<<endl;

 

第二个思路:

因为序列数据是两奇一偶,所以可以跳跃式累加

int sum = 2;
int cur_num = 2;
int prev_num = 1;

int next_num,next_next_num;

while(true)
{
next_num = prev_num + cur_num;
next_next_num = next_num + cur_num;
cur_num = next_num+next_next_num;
if(cur_num > 4000000)
{
break;
}
sum += cur_num;
prev_num = next_next_num;

}

cout<<sum<<endl;

以上是关于projecteuler第二题的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces/TopCoder/ProjectEuler 散题笔记 (持续更新)

projecteuler----&gt;problem=10----Summation of primes

Codeforces,Topcoder,SGU,Timus,ProjectEuler

Codeforces,Topcoder,SGU,Timus,ProjectEuler

简单的 Swift Fibonacci 程序崩溃(Project Euler 2)

ProjectEuler237 Tours on a 4 x n playing board