Problem 1 of Project Euler
If we list all the natural numbers below that are multiples of
or
, we get
,
,
and
. The sum of these multiples is
.
1 2 3 4 5 6 7 8 9 |
/* running a check on the first two statements by a direct computation */ #include <stdio.h>; #include <stdlib.h>; int main() { printf("The sum of all the natural numbers below 10 that are multiples of 3 and 5 is %d.", 3 + 5 + 6 + 9); system("pause"); return 0; } |
Find the sum of all the multiples of or
below
.
Ans.
(step-by-step approach, slow but sure logic)
I wish to find all the multiples of (excluding multiples of
) below
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/* finding all the multiples of 3 (excluding multiples of 5) below 1000*/ #include <stdio.h>; #include <stdlib.h>; int main() { int sum = 0; for (int i = 0; i < 1000; i += 3) { if (i % 5 != 0) { sum += i; } } printf("The sum of multiples of three (excluding multiples of five) below one thousand is %d.", sum); } |
1 2 |
Output. The sum of multiples of three (excluding multiples of five) below one thousand is 133668. |
Then I wish to find all the multiples of (excluding multiples of
) below
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/* finding all the multiples of 5 (excluding multiples of 3) below 1000:*/ #include <stdio.h>; #include <stdlib.h>; int main() { int sum = 0; for (int i = 0; i < 1000; i += 5) { if (i % 3 != 0) { sum += i; } } printf("The sum of multiples of five (excluding multiples of three) below one thousand is %d.", sum); } |
1 2 |
Output. The sum of multiples of five (excluding multiples of three) below one thousand is 66335. |
Lastly I wish to find all the multiples of below
:
1 2 3 4 5 6 7 8 9 10 11 12 |
/* finding all the multiples of 15 below 1000:*/ #include <stdio.h>; #include <stdlib.h>; int main() { int sum = 0; for (int i = 0; i < 1000; i += 15) { sum += i; } printf("The sum of multiples of fifteen below one thousand is %d.", sum); } |
1 2 |
Output. The sum of multiples of fifteen below one thousand is 33165. |
In sum,
Ans.
(to be continued)
Going off at a tangent, the sum of all numbers from to
is
. See:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <stdio.h>; #include <stdlib.h>; int main() { int i,sum; i = 1; sum = 0; do { sum += i++; } while (i <= 1000); printf("sum = %d", sum); system("pause"); return 0; } |
1 2 |
Output. sum = 500500 |
(proof)
(continue)
Solution. (fast and furious attempt)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/* The sum of all the multiples of 3 or 5 below 1000 */ #include <stdio.h>; #include <stdlib.h>; int main() { int sum = 0; int i = 0; while(i < 1000) { if(i % 3 == 0 || i % 5 == 0) sum += i; i++; } printf("The sum of all the multiples of 3 or 5 below 1000 is %d.", sum); } |
1 2 |
Output. The sum of all the multiples of 3 or 5 below 1000 is 233168. |