Skip to main content

Project Euler Solution 1

Problem Statement#

Add 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.

Solution#

This 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

  1. Check whether the number is a multiple of 3.

  2. 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.

Number3456789101112131415161718
3Y  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;
}

Sample Output#

Sample Output