Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of all the multiples of 3 or 5 below 1000

Tags:

python

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:

  1. 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.
  2. 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?
like image 269
Zach White Avatar asked Dec 05 '22 23:12

Zach White


2 Answers

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
like image 143
Eugene Sh. Avatar answered Dec 08 '22 12:12

Eugene Sh.


It is possible to do this in one line in Python using a generator expression:

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

The range(1000) produces all the integers from 0 to 999 inclusive. For each one of those integers, if it is divisible by 3 or divisible by 5, then it is included in the result. The sum(...) function adds up all those numbers, and finally print(...) prints the result.

like image 36
Greg Hewgill Avatar answered Dec 08 '22 13:12

Greg Hewgill