Project Euler - #1 Python wrong solution

2019-03-06 08:08发布

I am relatively new to coding in general and started Project Euler to bring my coding a bit further. Spent some time thinking of how to work the first question on my own and tried using recursive functions, unfortunately always getting the same mistake (266333). What did i miss? Any big mistake to learn from?

The original question reads: "If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000."

def function(i, j, h, k):
    if j < 1000 and k < 1000:
        i = i + j
        h = h + k
        return function(i, j+3, h, k+5)
    elif j < 1000 and k >= 1000:
        i = i + j
        return function(i, j+3, h, k)
    elif j >= 1000 and k < 1000:
        h = h + k
        return function(i, j, h, k+5)
    else:
        print (i + h)


function(0,0,0,0)

Where i is the sum of multiples of 3, h is the sum of multiples of 5, j is multiples of 3 and k is multiples of 5.

Problem source

2条回答
倾城 Initia
2楼-- · 2019-03-06 08:38

I'd strongly advise against recursion, since it might work for small number but not for bigger ones, and even if the solution might work, it would teach you a wrong approach.

def euler_1(sum, range_beg, range_end):
    for number in range( range_beg, range_end):
        if (( number % 3 ) == 0) or ((number % 5) == 0):
            sum += number
        else:
            pass

     return sum


print(euler_1( 0, 0, 1000))

This is more pythonic, reusable, faster and simpler to read and correct.

查看更多
Ridiculous、
3楼-- · 2019-03-06 08:50

Your mistake is that you are including numbers divisible by 15 twice: Once as a multiple of 3, and once as a multiple of 5.

For what it's worth, here's a concise way of computing this sum:

sum(i for i in range(1000) if not (i % 3 and i % 5))
查看更多
登录 后发表回答