Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the sum of all the multiples of 3 or 5 below 1000 in Python?

Not sure if I should've posted this on math.stackexchange instead, but it includes more programming so I posted it here.

The question seems really simple, but I've sat here for at least one hour now not figuring it out. I've tried different solutions, and read math formulas for it etc but it won't gives me the right answer when coding it! I made two different solutions for it, which both gives me the wrong answer. The first solution gives me 265334 while the second one gives me 232169. The answer is 233168, so the second solution is closer.

I should mention this is a question from Project Euler, the first one to be precise.

Here's my code. Any ideas what's wrong?

nums = [3, 5]
max = 999

result = 0
for num in nums:
    for i in range(1,max):
        if num*i < max:
            result += num*i
print result


result = 0
for i in range(0,max):
    if i%3 == 0 or i%5 == 0:
        result += i

print result
like image 469
qwerty Avatar asked May 08 '11 20:05

qwerty


People also ask

How do you find the sum of all the multiples of 3 or 5 below 1000?

here a is 3 or 5 or 15, and n is 999 or 1000 but 999 is best, and then sum multiples of 3: 3((333)∗(333+1)/2)=166833 plus multiples of 5: 5((199)∗(199+1)/2)=99500; and subtract multiples of 15 15((66)+(66+1)/2)=33165 to get 233168.

What is the sum of all multiples of 3 or 5?

Save this question. Show activity on this post. 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.

How do you find the sum of multiples in Python?

You can now use Python's built-in function sum() to add multiple numeric values together. This function provides an efficient, readable, and Pythonic way to solve summation problems in your code. If you're dealing with math computations that require summing numeric values, then sum() can be your lifesaver.


1 Answers

You are overcomplicating things. You just need a list of numbers that are multiples of 3 or 5 which you can get easily with a list comprehension:

>>> [i for i in range(1000) if i % 3 == 0 or i % 5 == 0]

Then use sum to get the total:

>>> sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])
<<< 233168

Or even better use a generator expression instead:

>>> sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0)

Or even better better (courtesy Exelian):

>>> sum(set(list(range(0, 1000, 3)) + list(range(0, 1000, 5))))
like image 155
zeekay Avatar answered Oct 03 '22 00:10

zeekay