Problem 1
Question
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.
Number
|
3
|
4
|
5
|
6
|
7
|
8
|
9
|
10
|
11
|
12
|
13
|
14
|
15
|
16
|
17
|
18
|
19
|
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.
Program
#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; }
Output
No comments:
Post a Comment