Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of multiples of 3 and 5

Tags:

python

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))
like image 650
TechMatt Avatar asked Jan 26 '23 14:01

TechMatt


1 Answers

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).

like image 80
hiro protagonist Avatar answered Jan 29 '23 03:01

hiro protagonist