PHP Solution to the Project Euler Problem 1

preuThis is one of the easiest problem in the project euler archive. You can perform this problem in any language of your choice. As this site is specifically for web developers so i’m focusing on php for this post. You can change the code to get answer in C, C++ or any other language of your choice. Depending on your language, few changes will be there but that’s upto you to fix. As this tutorial deals with the PHP code, I can tell you for sure that this code works.

You can check the problem here. It says :

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.

Thought Process – If you take a look at this problem you’ll observe that only numbers that are multiples of 3 and 5 are – 3, 5,6,9. You have to repeat this process for 1000 numbers in your program. Yes, you guessed it right we’re going to use loop in our program. We’re going to run a loop that counts upto 1000. We also need to check for the condition that checks the number is divisble by 3 and 5 and remainder is 0. In such case we’re going to use if condition inside our for loop to filter those numbers and it in our another variable that keep the sum.

You can see this in action in following code:

Code

<?php
$j=0;
$k=0;
for($j=1;$j<=1000;$j++)
{
    if($j%3==0 ||$j%5==0)
    $k+=$j;
}
echo "The sum of Multiples of 3 and 5 is: ",$k;
?>

This is very simple problem and I guess you should attempt it as much as possible before looking at this site for answer. If you manage to learn it in php, try to impement the logic in python or C# or C++. This will improve your language learning and logic too.

abu murad
Abu Murad , is fascinated by the constantly changing, complex, layered world of SEO, & content marketing’s ability to reach potential buyers on their terms, in their timing, and in the ways that are most relevant to them.

Leave a Comment