I have to calculate the sum of all the multiples of 3 and 5 (including themselves) in a range of a given N number (N excluded). I created a python code and it works with N = 10 but doesn't work for N = 100. I don't understand why.
This is the code:
#!/bin/python3
import sys
def multiples_sum(n):
sum1 = 0
for i in range(n):
if i % 3 == 0:
sum1 = sum1 + i
if i % 5 == 0:
sum1 = sum1 + i
return sum1
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
print(multiples_sum(n))
you are counting the multiples of 15 (= 3 * 5) twice.
your code should be
for i in range(n):
if i % 3 == 0:
sum1 += i
elif i % 5 == 0:
sum1 += i
note the elif
instead of if
.
alternatively:
for i in range(n):
if i % 3 == 0 or i % 5 == 0:
sum1 += i
or directly (as DeepSpace suggests in the comments)
sum1 = sum(i for i in range(n) if 0 in {i % 3, i % 5})
note that there is no need for looping at all: knowing that the sum of the integers from 1 to (and including) n
is
def sum_to(n):
return ((n+1)*n)//2
you can get your number from:
sum1 = 5 * sum_to((n-1)//5) + 3 * sum_to((n-1)//3) - 15 * sum_to((n-1)//15)
(that could be generalized and made somewhat prettier... but i'm sure you get the idea in this form).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With