patternpythonMajor
Project Euler #1: Multiples of 3 and 5
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.
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_sumSolution
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
Likewise the sum of all numbers less than 1000 that divides 5 is
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
The sum of all numbers less than 1000 that divides 15 is
So the final result is that the sum of all numbers less than 1000 that divides either 3 or 5 equals:
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)/2Likewise the sum of all numbers less than 1000 that divides 5 is
5*floor(999/5)*(floor(999/5)+1)/2Adding 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)/2So 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))/2Code Snippets
3*floor(999/3)*(floor(999/3)+1)/25*floor(999/5)*(floor(999/5)+1)/215*floor(999/15)*(floor(999/15)+1)/23 * (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))/2Context
StackExchange Code Review Q#102673, answer score: 23
Revisions (0)
No revisions yet.