第二日 斐波那契数列的偶数项和

Problem 2

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.
Haskell:

answer = sum [n|n<-takeWhile (<=4000000) fib,n`mod`2==0]
  where fib = 0:1:zipWith (+) fib (tail fib) 

C++:

#include<iostream>
using namespace std;
int main(){
unsigned long int a=1,b=2,c=0,sum=2;
while(1){
    if(c>=1000000) break;
    c=a+b;
    if(!(c%2)) sum += c;
    a=b;
    b=c;
}
cout<<sum;
return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • How to write cartoon writing? 一本正经的胡说八道 As i...
    膝盖中过箭阅读 1,495评论 0 0
  • 部署遇到的坑: 1.专案没有Merge 首先,我在项目rails_recipe终端那里,想要部署进去,发现错误了,...
    小耿_da0a阅读 3,698评论 0 0
  • po主唇部沙漠皮,容易起皮还手贱爱去撕⋯⋯总之唇纹不少,但是不觉得需要磨平它们,又不是充气娃娃。唇色略深,颜色不定...
    鹿子彦知Yoka阅读 1,547评论 0 0