第二日 斐波那契數列的偶數項和

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...
    膝蓋中過箭閱讀 221評論 0 0
  • 部署遇到的坑: 1.專案沒有Merge 首先,我在項目rails_recipe終端那里,想要部署進去,發現錯誤了,...
    小耿_da0a閱讀 595評論 0 0
  • po主唇部沙漠皮,容易起皮還手賤愛去撕??總之唇紋不少,但是不覺得需要磨平它們,又不是充氣娃娃。唇色略深,顏色不定...
    鹿子彥知Yoka閱讀 230評論 0 0