Chimeric Dream

My multi-faceted reverie

Project Euler Solution: Problem #1

Posted on: October 7th, 2009 by cdrmsuper No Comments

According to the Project Euler website, “Project Euler is a series of challenging mathematical/computer programming problems…”

Always a fan of puzzles, I have decided to share my attempts and solutions here.

Note: If you are trying to solve Problem #1 for yourself, DO NOT READ AHEAD!


Problem #1

Problem Description

Problem #1 entails finding the sum of all of the multiples of 3 or 5 under 1000.

Solution

This one was rather simple. The modulo mathematical operator (%) finds the remainder of one number divided by another. If the remainder is 0 (i.e. if x % y = 0), then x is a multiple of y.

Therefore, the task is simple: count from 1 to 999 (we want the numbers *below* 100, remember), check if n % 3 = 0 or n % 5 = 0. If either is a match, we add that to the running total.

Code (PHP)

1
2
3
4
5
6
7
$x = 0;
for ($i = 1; $i < 1000; $i++) {
    if ($i % 3 == 0 || $i % 5 == 0) {
        $x += $i;
    }
}
echo $x;

Total Sum: 233168

Tags: ,

No Responses

Leave a Reply