Project Euler Solution 1
#
Problem StatementAdd all the natural numbers below one thousand that are multiples of 3 or 5.
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.
#
SolutionThis problem calls for the sum of all natural numbers that are multiples of 3 or 5 below 1000. The smallest number which is a multiple of 3 or 5 is 3. So my starting number is 3. The terminating condition is also given in the problem as below 1000. Consider the following things while programming
Check whether the number is a multiple of 3.
Check if the number is multiple of 5 and not a multiple of 3.(This step is to avoid adding duplicate numbers).
Finding the sum of all multiples of 3 or 5 below 20.
Initially sum = 0
3 is the smallest number that is a multiple of 3 or 5.
Number | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
3 | Y | Â | Â | Y | Â | Â | Y | Â | Â | Y | Â | Â | Y | Â | Â | Y |
5 | Â | Â | Y | Â | Â | Â | Â | Y | Â | Â | Â | Â | Y | Â | Â | Â |
note
Shaded box represents that the number is divisible by either 3 or 5 or both.
15 is divisible by 3 and 5, so it is sufficient to check and add only once.
#
Implementation#include <stdio.h>
int main(){ int sum, number; sum = 0; for (number = 3; number < 1000; number++) { if ((number % 3) == 0) sum = sum + number; else if ((number % 5) == 0) sum = sum + number; } printf("sum :%d", sum); return 0;
}