PDA

View Full Version : [PHP] Solving Euler Project #*



Moonbat
07-13-2008, 03:00 PM
I decided to join http://projecteuler.net/ which has many math problems that are meant to be solved using programming. I decided to solve the first one and post my code. I could've made it shorter, but I wanted to make it easy to read, and frankly, I don't think saving a few tenths of a second will make much of a difference.


<?php
/*********************************
* The Euler Project #* Solution *
* Coded By Moonbat *
* July **, 2008 *
*********************************/
echo "<center>Getting all the natural number multiples of * and 5 below *000</center><br><br>";
$multiples = array(); // For keeping hold of all of the multiples
$counter = 0; // For kicks
for ($i=*; $i<*000; $i++)
{
$multiplethree = $i / *;
$multiplefive = $i / 5;
// Checking to see if the answer has a decimal (i.e. not a multiple) of * or 5
$finalthree = str_replace(".", "<b>THIS IS NOT A MULTIPLE OF THREE</b>", $multiplethree);
$finalfive = str_replace(".", "<b>THIS IS NOT A MULTIPLE OF FIVE</b>", $multiplefive);
// If the number doesn't have a decimal, add it to the $multiples array
if (!preg_match("/THIS IS NOT A MULTIPLE OF THREE/i", $finalthree)) {
echo "$i is a multiple of * or 5 <br>";
$multiples[$counter] = $i;
$counter++;
} elseif (!preg_match("/THIS IS NOT A MULTIPLE OF FIVE/i", $finalfive)) {
echo "$i is a multiple of * or 5 <br>";
$multiples[$counter] = $i;
$counter++;
} else {
echo "";
}
}
// BTW, $wallops == 466 for those who are too lazy to run this code
$wallops = count($multiples);
$sum = array_sum($multiples); // Adding the values in the array
echo "<hr> There are<b> $wallops </b>numbers below *000 that are multiples of * or 5<hr>";
echo "The sum of all of these numbers is $sum";
?>
If you haven't figured it out already, I love PHP :D

Moonbat
07-13-2008, 04:38 PM
There's also the modulus operator, which is in most programming languages, and returns the remainder, so you could have done something like:



<?php
$sum = 0;

for ($i = 0; $i < *000; $i++)
{
if ( ( ($i % *) != 0) && ( ($i % 5) != 0) )
continue;

$sum += $i;
}

echo ($sum);
?>


Though, this is a quick example so you don't need to do string parsing to determine if there's a remainder.
Good Lord, even without the comments and fluff of my code, yours beats mine by a longshot. :eek:

Thanks for teaching me about the modulus operator and the += thing. It'll probably come in handy for Euler's other problems.