Pages

February 23, 2011

Project Euler 1

Problem #1. Add all the natural numbers below one thousand that are multiples of 3 or 5.

Solution : This can be done in two ways ....

i. The normal method, i.e. run a for from 1 to 1000 and check for the given condition on each number.
This method does solves our problem but is crude.

upperlimit=999
total_sum=0
for i=1 to upperlimit do
if (i mod 3=0) or (i mod 5)=0 then
total_sum:=total_sum+i;
output total_sum


ii. The short-cut method : In this you need only one formula and just need to compute value of 3 expressions.
Just go through---->

The solution to given problem will be the answer of this expression :
ans = sumDivisibleBy(3) + sumDivisibleBy(5) - sumDivisibleBy(15)

Now for n=3 :
3,6,9,12,15,18,21,24,27,.....,999 = 3(1,2,3,4,5,6,7,8,9,....,333)

Now we know that :
1 + 2 + 3 + .... + q = 1/2*q*(q+1)

In our case : q = upperlimit / n
Therefore our solution says :

Function sumDivisibleBy(n):
q = upperlimit div n
return n*(q*(q+1)) div 2
EndFunction

print sumDivisibleBy(3)+sumDivisibleBy(5)-sumDivisibleBy(15)


Feel free to ask any kind of querry, I'll try my best to solve it.

Enjoy coding :-)

No comments:

Post a Comment