Sum of all the multiples of 3 or 5 below 1000

python

Solution

Actually this problem can be solved in O(1) instead of O(N) without using any loops or lists:

The required sum is the sum of all multiples of 3 plus sum of all multiples of 5 minus the sum of multiples of (3*5=15) below the given number 1000 (LIMIT=999). The sums are calculated as a sum of arithmetic series. It can be calculated in following way:

LIMIT=999

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

# calculate 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 total
total = sum_three + sum_five - sum_fifteen

# print result with Python 3
print(int(total))

The result is:

>>> 
233168

Problem

Beginner here- trying to make a simple python program that will compute/answer this problem: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Currently this is what I have: ``` a = 0 b = 0 while a < 1000: a = a + 3 print (a) while b < 1000 b = b + 5 print (b) ``` This will print all the numbers being considered. I just need to add them together and that's my answer. I would like one of two things to happen, instead of the code that I have written: - I would like all of this to happen internally, and therefore not have to use the "print" function. The just print the sum of all of those multiples. - I would like all of this stuff to print, but then I want to be able to print the sum of all of them too. Is there a way to make the computer take the value of everything it has printed?

Original source