Project Euler 1: Sum of the Multiples of 3 and 5
Project Euler is a cool site that I just stumbled upon. It contains problems which require both mathematics and programming to succeed. I decided to start writing a guide for Project Euler for those who need a little help. I will never write the complete answer, since you’ve got to do something by yourself. The first problem is straight-forward:
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.
You can solve this either through mathematics or through programming. If you want to go the mathematician’s way, you must first write an expression for it. The sum of the series is essentially the sum of two other series; the multiples of 3 below 1000 and the multiples of 5 below 1000. For the sum of these series, use the following formula:

n is the number of elements in the series. Therefore it equals 333 (999/3) for the first sum and 199 (999/5, rounded down) for the second one. a1 is the first element, i.e. 3 and 5, respectively. an is the last element. That is 999 for the first (333*3) and 995 for the second (199*5). Now, we have:

Note, however, that there is a flaw here. The numbers which are multiples of both 3 and 5 are counted twice! In order to fix this, we need to find out which numbers are multiples both numbers. Of course, those numbers are the numbers divisible by the lowest common denominator of 3 and 5. That is 15. We will then subtract all numbers which are multiples of 15 in a similar way:

You’ve got to calculate it yourself.
It is much easier and faster (but less cool) to write a program which does the job for you. This perl script does the task well:
1 2 3 4 5 6 7 | my $s = 0; for ( my $n = 0; $n < 1000; $n++ ) { if ( ! ( $n % 3 && $n % 5 ) ) { $s += $n } } print $s; |
- Line 1 sets
$s(the sum) to 0, just to be sure. - Line 2 starts the loop which will loop for
$n(the current number) from 0 to 999. - Line 3 checks whether
$nis divisible by either 3 or 5. - Line 4 adds
$nto$s - Line 7 prints the final sum.

Hi,
Nice work. First it is hard for me to understand what line 3 is doing, as I think that u r not counting the numbers which can be divided by 3 and 5, due to !. But then I understand that you used modulo operator and it worked in different fashion, i.e. returns 0 is they are divisible.
Thanks,
Keep it up.
Comment by Hts Hack — January 12, 2008 @ 4:39 pm
hi i tried to code your perl programm in c++
and i got this answer
166841
is this the correct one ?
Comment by manzoor — February 26, 2008 @ 3:43 pm
manzoor: I just ran the script, and that seems not to be the case.
Comment by Tim — June 19, 2008 @ 10:06 am