计算斐波那契数列中偶数值项的和
#!/usr/bin/python2
"""
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.
"""
odd, even = 0,1
total = 0
while True:
odd = odd + even #Odd
even = odd + even #Even
if even < 4000000:
total += even
else:
break
print total
我的算法:
- 我把前两个数字设为0和1;在循环中我首先找到的数字会是一个奇数,也是斐波那契数列的第一个数字。
- 这样我就能计算出偶数,每次把这个偶数的值加到总数里。
- 如果这个
even
的值超过4000000,我就会退出这个无限循环。
我尝试了很多次,但我的答案总是错的。网上查的资料说答案应该是4613732
,但我总是得到5702886
。
25 个回答
4
这里有一个简单的C语言解决方案:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=1,j=1,sum=0;
while(i<4000000)
{
i=i+j;
j=i-j;
if(i%2==0)
sum+=i;
}
printf("Sum is: %d",sum);
}
4
在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这种时候,我们可以去一些技术论坛,比如StackOverflow,去寻找解决方案或者向其他人提问。
在这些论坛上,很多人会分享他们的经验和解决方法。你可以看到他们的提问和回答,了解别人是怎么解决类似问题的。这不仅能帮助你解决眼前的问题,还能让你学到更多的知识。
记得在提问的时候,要把问题描述清楚,这样别人才能更好地帮助你。同时,查看一下是否有人已经问过类似的问题,这样可以节省时间。
总之,技术论坛是一个很好的学习和交流的地方,适合所有想要提高编程技能的人。
def fibonacci_iter(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
print sum(a for a in fibonacci_iter(4e6) if not (a & 1))
25
基本上,你现在做的是把斐波那契数列中的每个第二个元素都加起来,而题目要求的是只加偶数元素。
你应该做的是遍历所有小于4000000的斐波那契数值,然后用 if value % 2 == 0: total += value
来判断。这里的 %
是取余运算符,如果一个数除以2的余数是0,那这个数就是偶数。
举个例子:
prev, cur = 0, 1
total = 0
while True:
prev, cur = cur, prev + cur
if cur >= 4000000:
break
if cur % 2 == 0:
total += cur
print(total)