Project Euler problem:
If we list all the natural numbers below
10that are multiples of3 or 5, we get3, 5, 6 and 9
Some numbers will be divisible by both 3 and 5, you should not add them twice. A code like this will give correct result:
long int x,total = 0;
for(x = 0; x < 1000; ++x)
{
if(x % 3 == 0)
total = total + x;
else if(x % 5 == 0)
total = total + x;
}
printf("%ld", total);
in the code above if else if make sure that if a number is divisible by 3 or by 5. And allow to sum up on this basis.
It can further be optimized to:
for(x= 0; x < 1000; ++x)
{
if(x%3 == 0 || x%5 == 0)
total = total + x;
}
Above solution is O(n) for better time complexity O(1) we can use Arithmetic Progression with interval of 3 and 5.
n = total number of multiples of given number(Num) in given range (1...R). in this case (1...1000)
a1 = first multiple. Here it will be 3 or 5.
an = last multiple. i.e 3Xn
Hence, following code will calculate Sum of series with interval 3/5 (Num) for given range 1...lastOfRange (excluding lastOfRange).
long SumOfSeries(long Num, long lastOfRange)
{
long multiplesCount = (lastOfRange-1) / Num; //(lastOfRange-1) to exlude the last number 1000 here
long result = multiplesCount * (Num + (multiplesCount * Num)) / 2;//Num = a1, (multiplesCount * Num) = an.
return result;
}
and this can be called as:
long N = 1000;
Sum = SumOfSeries(3, N) + SumOfSeries(5, N) - SumOfSeries(3*5, N);
printf("%ld", total);