import time
start = time.time()
NUM = 0
看了结果,我这错的没边儿了 马上大二,打卡打卡
感谢小甲鱼 /*
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.
题目翻译:
斐波那契数列中的每一项被定义为前两项之和。
从 1 和 2 开始,斐波那契数列的前十项为:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
考虑斐波那契数列中数值不超过 4 百万的项,找出这些项中值为偶数的项之和。
*/
#include <bits/stdc++.h>
using namespace std;
long long ans; // 记录答案
long long a = 1, b = 2, c = a + b, tmp;
int main() {
while (c <= 4000000) {
if (c % 2 == 0) ans += c;
c = a + b; a = b; b = c;
}
cout << ans << endl;
return 0;
}
输出为4613730 111 public static void main(String[] args) {
int res = getSum(4000000);
System.out.println(res);
}
private static int getSum(int n) {
int sum = 0;
if (n < 2) return sum;
int i = 1, j = 2;
while (j <= n) {
if (j % 2 == 0) sum += j;
j += i;
i = j - i;
}
return sum;
} 学习 a=1
b=1
answer=0
while a<=4000000:
if not a%2:
answer+=a
a,b = b,a+b
else:
print(answer) 学习学习! def fib(n):
fibseq =
result = 0
while fibseq[-1]<n:
if fibseq[-1] % 2 == 0:
result += fibseq[-1]
fibseq.append(fibseq[-1]+fibseq[-2])
return result
print(fib(4000000)) 每三位出现一个偶数,每次算三位就不需要检查偶数了
ulong test2 (ulong n)
{
ulong res = 0;
ulong first = 1, second = 1, Xn = 0;
while ((Xn = first + second) < n)
{
res += Xn;
first = second+Xn;
second = first+Xn;
}
return res;
}
int main (int argc, char *argv[])
{
auto res = test2 (4000000);
std::cout << res << std::endl;
} test 开眼界了,还有这汇总项目 学习了 sum = 0
a = 1
b = 2
while b <= 4000000:
if b % 2 == 0:
sum += b
a, b = b, a + b
print(sum)
页:
1
[2]