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:
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開始生成的斐波那契數列前10項爲:
考慮該斐波那契數列中不超過四百萬的項,求其中爲偶數的項之和。
剛開始做這道題覺得暴力算是不可行的
後來實在沒想到其他好方法
就暴力算吧
後來遇到的困難就是我自己想出來的斐波那契數列是有3個變量的那種
就是一開始定義3個變量a、b、c
然後a=1;b=2;
c=a+b;
a=b+c;
b=a+c;
後來判定是否爲偶數時遇到困難
#include<iostream>
void fun(int n)
{
int a = 1, b = 2, c , sum=0;
while (b<n)
{
if (b % 2 == 0)
sum = sum + b;
b = a + b;
a = b - a;
}
std::cout << "Output:" << sum << std::endl;
}
void main()
{
fun(4000000);
system("pause");
}
最後的結果爲4613732