小于 400 万的偶数斐波那契数的总和 - Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23168502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum of even fibonacci numbers below 4 million - Python
提问by nonsequiter
I'm attempting the second Project Euler question in python and want to understand why my code doesn't work.
我正在尝试在 python 中解决第二个 Project Euler 问题,并想了解为什么我的代码不起作用。
This code finds the sum of even Fibonacci numbers below 4 million
此代码查找小于 400 万的偶数斐波那契数的总和
counter = 2
total = 0
while counter <= 4000000:
if counter % 2 == 0:
total+= counter
counter+= (counter -1)
print total
This code will output: 2
此代码将输出:2
If I print the counter it outputs: 4194305
如果我打印计数器,它会输出:4194305
I'm assuming it's an issue with the if statement being executed as the while loop is functioning correctly and the counter is also incrementing correctly.
我假设这是 if 语句的问题,因为 while 循环运行正常并且计数器也正确递增。
采纳答案by freakish
The problem is in the line counter+= (counter -1)
. You add it to itself (minus 1) while you should be doing this:
问题出在线路上counter+= (counter -1)
。您应该在执行此操作时将其添加到自身(减去 1):
a, b = 1, 1
total = 0
while a <= 4000000:
if a % 2 == 0:
total += a
a, b = b, a+b # the real formula for Fibonacci sequence
print total
回答by Roberto Reale
The algorithm should be fixed. In your code you are not summing up Fibonacci numbers.
算法应该是固定的。在您的代码中,您不是在总结斐波那契数。
Here is a revised version:
这是一个修订版:
total = 0
i, j = 1, 0
while j <= 4000000:
if j % 2 == 0:
total += j
i, j = j, i + j
print total
回答by Valdrinium
First of all, you should generate all fibonacci numbers below 4000000 using the recursive formula and for each number, if it is even, you add it to the sum.
首先,您应该使用递归公式生成所有 4000000 以下的斐波那契数,对于每个数,如果是偶数,则将其添加到总和中。
The formula:
公式:
回答by user3485986
well algorithms is wrong.
counter is always odd, well it's even only in the begining. this is how it goes
2
3
5
9
17
and so on. total+= counter
is never executes
好吧算法是错误的。counter 总是奇怪的,它甚至只是在开始时。这就是它的方式 2 3 5 9 17 等等。total+= counter
永远不会执行
回答by jonrsharpe
The series your code calculates for counter
is as follows:
您的代码计算的系列counter
如下:
2 # solid start
3 # good
5 # this is going great
9 # wait, what?
17 # this is going really badly
You can't just add counter - 1
each time, you need to add the previous number in the series.
您不能counter - 1
每次都添加,您需要添加系列中的前一个数字。
So why is your total
so small? Because an odd number minus one is always even, and an odd number plus an even number is always an odd number; 2
is the only even number you ever generate, hence that is your total
.
那你total
怎么这么小?因为奇数减一永远是偶数,奇数加偶数永远是奇数;2
是您生成的唯一偶数,因此这是您的total
.
Generating the Fibonacci numbers is typically done with two variables a
and b
, where we start
生成斐波那契数通常使用两个变量a
和b
,我们从这里开始
a = b = 1
and each iteration looks like:
每次迭代看起来像:
a, b = b, a + b
回答by thebjorn
There are easier ways to do this (e.g. freakish's solution), but this version says what it does and does what it says :-)
有更简单的方法可以做到这一点(例如,freakish 的解决方案),但这个版本说明了它的作用和它所说的:-)
from itertools import takewhile
def fibonacci():
a, b = 1, 1
while 1:
yield a
a, b = b, a+b
def even(it):
for n in it:
if n % 2 == 0:
yield n
print sum(takewhile(lambda f: f <= 4000000, even(fibonacci())))
回答by Roger Fernandez Guri
If you watch closely, you'll see the following sequence:
如果仔细观察,您会看到以下序列:
1 1 2 3 5 8 13 21 34 55 89 144 ...
1 1 2 3 5 8 13 21 34 55 89 144 ...
The formula for mapping the Fibonacci sequence is:
映射斐波那契数列的公式是:
And you only want the sum of the evennumbers such as:
而且您只需要偶数的总和,例如:
1 1 23 5 813 21 3455 89 144...
1 1 23 5 813 21 3455 89 144...
So you can map a new formula such as:
因此,您可以映射一个新公式,例如:
And you will obtain the following sequence:
您将获得以下序列:
2 8 34 144 ...
2 8 34 144 ...
Code example (Go):
代码示例(Go):
package main
import "fmt"
func fibonacci() func() int {
first, second := 0, 2
return func() int {
ret := first
first, second = second, first+(4*second)
return ret
}
}
func main() {
sum := 0
f := fibonacci()
for i := 0; sum < 4000000; i++ {
sum += f()
}
fmt.Println(sum)
}
In that case you will not need the if conditionals.
在这种情况下,您将不需要 if 条件。
Hope that helped you! Cheers!
希望对你有帮助!干杯!
回答by Konrad
#include <iostream>
using namespace std;
int main()
{
int total, a=1,b=2,c;
while(a+b<4000000)
{
if(b%2==0)
{
total+=b;
}
c=a+b;
a=b;
b=c;
}
cout<<total;
return 0;
}
回答by SupAl
Here's my Python code. I make use of 2 things. First, that the nth fibonacci number can be calculated as:
Fibn= [φn-(1-φn)]/√5,
and the fact that even numbers occurs at every 3 Fibonacci number. This avoids a lot of unnecessary computation!
这是我的 Python 代码。我利用了两件事。首先,第 n 个斐波那契数可以计算为:
Fib n= [φ n-(1-φ n)]/√5,
并且偶数出现在每 3 个斐波那契数上。这避免了很多不必要的计算!
import numpy as np
import time
start = time.perf_counter()
phi_p = (np.sqrt(5)+1)/2
phi_n = phi_p-1
sqrt5_inv = 1/np.sqrt(5)
def Fib(n):
return int(sqrt5_inv*((phi_p)**n-(-phi_n)**n))
fib_e_sum = 0
index = 3
max_fib = 4e6
tmp_fib = 0
while (tmp_fib<max_fib):
fib_e_sum += tmp_fib
tmp_fib=Fib(index)
index += 3
end = time.perf_counter()
total_time = end-start
print(fib_e_sum)
print(total_time)
回答by Asrorkhuja Ortikov
Well I have tried this way:
好吧,我已经尝试过这种方式:
fib_num = [0 ,1]
for i in range(2, 4*10**6):
fib_num.append(fib_num[i-1] + fib_num[i-2])
def even_fib(fib_num):
result = 0
result = result + sum([even for even in range(0, fib_num) if even % 2 == 0])
print result
Whats wrong with that? It is taking too long to respond for script and giving 'killed' error
那有什么问题?响应脚本并给出“已终止”错误花费的时间太长