Karam Dakka
Karam Dakka

Reputation: 1

Find the sum of all the multiples of 3 or 5 below 1000. (idk what is wrong with my code)

I'm a beginner and I tried this code to list the sum of all the multiples of 3 or 5 below 100, but it gives a wrong answer and I don't know why.

result = 0
result2 = 0
som = 0
sum2 = 0
below_1000 = True
while below_1000:
    result = result+3
    if result < 1000:
        som += result
    else:
        below_1000 = False
below_1000 = True
while below_1000:
    result2 = result2+5
    if result2 < 1000:
        sum2 += result2
    else:
        below_1000 = False
        final_result = som+sum2
print(final_result)

Upvotes: 0

Views: 74

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117876

Since you first loop over multiples of 3, then again over multiples of 5, you are double-counting a lot of values, specifically values that are multiples of both 3 and 5 (for example 15 or 60).

To write this manually, you can use a for loop over range

total = 0
for i in  range(1000):
    if i % 3 == 0 or i % 5 == 0:
        total += i

>>> total
233168

A more concise way to do this same thing is using a generator expression within the sum function

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

Upvotes: 3

Related Questions