pythonfor-loopmultiple-select

Finding all the multiples of 3 and 5 in the range of 100 using for loop


I'm an absolute beginner to programming and I've been doing simple tasks like this one. And I dont really see how I'm getting 2 different results in these codes below.

total1 = 0
for element in range(1, 100):
    if element % 3 == 0:
        total1 = total1 + element
print(total1)
#1683

total2 = 0
for element in range(1, 100):
    if element % 5 == 0:
        total2 = total2 + element
print(total2)
#950

print(total1 + total2)
#2633

And then a different way of computing the multiples giving me a different result.

total = 0
for element in range(100):
    if element % 3 == 0 or element % 5 == 0:
        total += element
print(total)
#2318

Mathematically if I'm not wrong the sum of the multiples of number 3 and 5 in the range of 100 is 2633 but I cannot figure out why the other solution gives me 2318.

Thank you for the help in advance!


Solution

  • The difference is when element is a number that is both divisible by 3 and 5. In your first method, that number will be added to the total twice, whereas in the second it will only be added once.

    You can check it by looking at what happens in each case when element = 15 for example. In your first code, both total1 and total2 will add 15, making the sum of total1 + total2 = 30. Whereas in the second method, you only add 15 to the total once, making the overall total just 15.

    You need to work out which method you want to happen when a number is divided by both, should it be added twice? or just once?