Project Euler problem:
If we list all the natural numbers below
10that are multiples of3 or 5, we get3, 5, 6 and 9
The answer can be computed with simple arithmetic without any iteration. Many Project Euler questions are intended to make you think about clever ways to find solutions without just using the raw power of computers to chug through calculations.
Given positive integers N and F, the number of positive multiples of F that are less than N is floor((N-1)/F). (floor(x) is the greatest integer not greater than x.) For example, the number of multiples of 5 less than 1000 is floor(999/5) = floor(199.8) = 199.
Let n be this number of multiples, floor((N-1)/F).
The first multiple is F and the last multiple is n•F. For example, with 1000 and 5, the first multiple is 5 and the last multiple is 199•5 = 995.
The multiples are evenly spaced, so the average of all of them equals the average of the first and the last, so it is (F + nF)/2.
The total of the multiples equals their average multiplied by the number of them, so the total of the multiples of F less than N is n • (F + n•F)/2.
As we have seen in other answers and in comments, adding the sum of multiples of 3 and the sum of multiples of 5 counts the multiples of both 3 and 5 twice. We can correct for this by subtracting the sum of those numbers. Multiples of both 3 and 5 are multiples of 15.
Thus, we can compute the requested sum using simple arithmetic without any iteration:
#include
static long SumOfMultiples(long N, long F)
{
long NumberOfMultiples = (N-1) / F;
long FirstMultiple = F;
long LastMultiple = NumberOfMultiples * F;
return NumberOfMultiples * (FirstMultiple + LastMultiple) / 2;
}
int main(void)
{
long N = 1000;
long Sum = SumOfMultiples(N, 3) + SumOfMultiples(N, 5) - SumOfMultiples(N, 3*5);
printf("%ld\n", Sum);
}
As you do other Project Euler questions, you should look for similar ideas.