简体   繁体   English

欧拉2专案python3

[英]Project Euler 2 python3

I've got, what I think is a valid solution to problem 2 of Project Euler (finding all even numbers in the Fibonacci sequence up to 4,000,000). 我得到了我认为是对Euler项目问题2的有效解决方案(在Fibonacci序列中查找所有偶数,最大为4,000,000)。 This works for lower numbers, but crashes when I run it with 4,000,000. 这适用于较小的数字,但是当我以4,000,000运行时会崩溃。 I understand that this is computationally difficult, but shouldn't it just take a long time to compute rather than crash? 我知道这在计算上很困难,但不是应该花很长时间计算而不是崩溃吗? Or is there an issue in my code? 还是我的代码有问题?

import functools

def fib(limit):
    sequence = []
    for i in range(limit):
    if(i < 3):
        sequence.append(i)
    else:
        sequence.append(sequence[i-1] + sequence[i-2])
    return sequence

def add_even(x, y):
    if(y % 2 == 0):
        return x + y
    return x + 0

print(functools.reduce(add_even,fib(4000000)))

The problem is about getting the Fibonacci numbers that are smaller than 4000000. Your code tries to find the first 4000000 Fibonacci values instead. 问题是有关获取小于4000000的斐波那契数的。您的代码尝试查找前4000000斐波那契值。 Since Fibonacci numbers grow exponentially, this will reach numbers too large to fit in memory. 由于斐波那契数呈指数增长,因此该数将达到太大而无法容纳在内存中。

You need to change your function to stop when the last calculated value is more than 4000000. 您需要将函数更改为在上一次计算的值大于4000000时停止。

Another possible improvement is to add the numbers as you are calculating them instead of storing them in a list, but this won't be necessary if you stop at the appropriate time. 另一个可能的改进是在计算数字时将其添加而不是将其存储在列表中,但是如果您在适当的时间停下来,则不需要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM