HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMajor

Project Euler #1: Multiples of 3 and 5

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andprojectmultipleseuler

Problem

Challenge Description:


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.

Source

I want to receive advice on my code.

total_sum = 0
for i in range(1000):
    if (i%3 == 0 or i%5 == 0):
        total_sum = total_sum+i
print total_sum

Solution

You don't need iteration at all for this problem.

Consider; the sum of all numbers from 1 to n is equal to n*(n+1)/2. Also the sum of all numbers less than n that divides d equals d times the sum of all numbers less than n/d.

So the sum of all numbers less than 1000 that divides 3 is

3*floor(999/3)*(floor(999/3)+1)/2


Likewise the sum of all numbers less than 1000 that divides 5 is

5*floor(999/5)*(floor(999/5)+1)/2


Adding the two numbers would overcount though. Since the numbers that divides both 3 and 5 would get counted twice. The numbers that divides both 3 and 5 is precisely the numbers that divides 3*5/gcd(3,5)=15/1=15.

The sum of all numbers less than 1000 that divides 15 is

15*floor(999/15)*(floor(999/15)+1)/2


So the final result is that the sum of all numbers less than 1000 that divides either 3 or 5 equals:

3 * (floor(999/3)  *  (floor(999/3)+1))/2
+ 5 * (floor(999/5)  *  (floor(999/5)+1))/2
-15 * (floor(999/15) * (floor(999/15)+1))/2

Code Snippets

3*floor(999/3)*(floor(999/3)+1)/2
5*floor(999/5)*(floor(999/5)+1)/2
15*floor(999/15)*(floor(999/15)+1)/2
3 * (floor(999/3)  *  (floor(999/3)+1))/2
+ 5 * (floor(999/5)  *  (floor(999/5)+1))/2
-15 * (floor(999/15) * (floor(999/15)+1))/2

Context

StackExchange Code Review Q#102673, answer score: 23

Revisions (0)

No revisions yet.