I recently came across Project Euler. This is a collection of problems needing some combination of maths and programming to solve.
I will try to solve one problem everyday and post the solutions here. The first few problems are hopefully relatively straightforward - fingers crossed.
Problem 1:
" 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.
S = Sum_i (1 to int[N/3]) 3i + Sum_i (1 to int[N/5]) 5i - Sum_i (1 to int[N/15]) 15i
=> S = 3* ( int[N/3] * (int[N/3] +1)/2 ) + 5* ( int[N/5] * (int[N/5] +1)/2 ) - 15* ( int[N/15] * (int[N/15] +1)/2 )
Plugging N = 999;
S = 3*333*334/2 + 5*199*200/2 - 15*66*67/2
= 233168
I will try to solve one problem everyday and post the solutions here. The first few problems are hopefully relatively straightforward - fingers crossed.
Problem 1:
" 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."
Solution:
To get this, one just needs to sum all the multiples of 3 and 5 and subtract the double countings (multiples of 15).
So for the sum for all such numbers below N;
=> S = 3* ( int[N/3] * (int[N/3] +1)/2 ) + 5* ( int[N/5] * (int[N/5] +1)/2 ) - 15* ( int[N/15] * (int[N/15] +1)/2 )
Plugging N = 999;
S = 3*333*334/2 + 5*199*200/2 - 15*66*67/2
= 233168
No comments:
Post a Comment