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

2 Answers

0 votes
result = sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0)

print(result)



'''
run:

233168

'''

 



answered Apr 14 by avibootz
0 votes
LIMIT = 999

# Get the upper bounds 
upper_for_three = LIMIT // 3
upper_for_five = LIMIT // 5
upper_for_fifteen = LIMIT // 15

# calculate the sums
sum_three = 3 * upper_for_three * (1 + upper_for_three) / 2
sum_five = 5 * upper_for_five * (1 + upper_for_five) / 2
sum_fifteen = 15 * upper_for_fifteen * (1 + upper_for_fifteen) / 2

# calculate the total sum
total_sum = int(sum_three + sum_five - sum_fifteen)

print(total_sum)



'''
run:

233168

'''

 



answered Apr 14 by avibootz
...