题目2:在斐波那契数列中,找出所有值不大于4,000,000,并且为偶数的项之和
本帖最后由 欧拉计划 于 2023-7-4 19:15 编辑题目2:在斐波那契数列中,找出所有值不大于4,000,000,并且为偶数的项之和
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 百万的项,找出这些项中值为偶数的项之和。
视频讲解:
https://www.bilibili.com/video/BV1Tk4y1773d
思路解析及源码参考(C & Python):
**** Hidden Message *****
#include <bits/stdc++.h>
using namespace std;
long long f, ans = 0;
int main() {
f = 1;
f = 2;
for (int i = 3; i <= 50 && f <= 4000000; ++i) {
f = f + f;
if (f % 2 == 0) ans += f;
}
printf("%lld\n", ans);
return 0;
} #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 55,INF = 4000000;
int f;
LL ans=2;
int main()
{
f = 1;
f = 2;
for(int i=3;f<=INF;i++)
{
f = f + f;
if(f<=INF&&f%2==0) ans += f;
}
cout<<ans<<endl;
return 0;
} 1 list1 =
while list1[-1] <= 4000000 * (pow(5,1/2)-1)/2:
list1.append(list1[-2]+list1[-1])
print(sum()) 学习 def fib():
fib1, fib2 = 1, 1
while True:
yield fib1
fib1, fib2 = fib2, fib1 + fib2
sum = 0
f = fib()
for x in f:
if x > 4000000:
break
else:
if x % 2 == 0:
sum += x
print(f"值为偶数的项之和:{sum}") 开看 学习学习 111 {:10_277:} 2 6 Rust代码
fn fibonacci_sum(n: i64) -> i64 {
let mut v: Vec<i64> = .to_vec();
let mut i = 2;
while v <= n {
v.push(v + v);
i += 1;
}
v.iter().filter(|&&i| i % 2 == 0).sum()
} a = []
i = 1
j= 2
sum = 0
while i <= 4000000:
a.append(i)
if i % 2 == 0:
sum += i
i, j = j, i+j
print("偶数项的和为:%d" % sum)
print(a)
偶数项的和为:4613732
fn main() {
let mut fibonacci: Vec<u32> = vec!;
let mut i = 2;
while fibonacci + fibonacci <= 4000000 {
fibonacci.push(fibonacci + fibonacci);
i += 1;
}
let sum: u32 = fibonacci.iter().filter(|x| *x % 2 == 0).sum();
println!("数列为:{:?}", fibonacci);
println!("偶数项的和为:{}", sum);
} #include <stdio.h>
int main(void) {
int a = 1,b=2,sum = 2;
int c = a + b;
while(c < 4000000){
if (c % 2 == 0){
sum += c;
}
a = b;
b = c;
c = a + b;
}
printf("%d\n", sum);
return 0;
} 111111111111 打卡 import time
start = time.time()
NUM = 0
xulie =
for i in range(len(xulie)):
xin = xulie + xulie
for k in range(1, xin):
NUM = NUM + k
print(NUM)
end = time.time()
print(end-start)
这么写的,运行了有结果,但不知道对不对,特来验证
页:
[1]
2