By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

July 30, 2011

Project Euler Problem 2

<?php

/*
Problem 2
19 October 2001

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.*/

print "By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

\n";

define('MAX_NUM', 4000001); // thru and including 4 million
define('DIVISOR', 2);

$previous1_term = 1;
$previous2_term = 2;
$sum = 0;
while($previous1_term < MAX_NUM
|| $previous2_term < MAX_NUM)
{
if($previous1_term < MAX_NUM
&& ($previous1_term % DIVISOR) === 0)
{
$sum = $sum + $previous1_term;
print "$previous1_term + ";
}
if($previous2_term < MAX_NUM
&& ($previous2_term % DIVISOR) === 0)
{
$sum = $sum + $previous2_term;
print "$previous2_term + ";
}
$previous1_term = $previous1_term + $previous2_term;
$previous2_term = $previous1_term + $previous2_term;
}
print "

sum: $sum";

?>


Add all the natural numbers below one thousand that are multiples of 3 or 5.

July 30, 2011

Project Euler Problem 1


<?php

/*
Problem 1
05 October 2001

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.
*/

print "Find the sum of all the multiples of 3 or 5 below 1000.

\n";

define('MAX_NUM', 1000);
define('LOWEST_DIVISOR', 3);
define('DIVISOR_2', 5);

$i = 1;
$sum = 0;
while($i < MAX_NUM)
{
$add_i = false;
if(($i % LOWEST_DIVISOR) === 0)
{
$sum = $sum + $i;
$add_i = true;
}
else if(($i % DIVISOR_2) === 0)
{
$sum = $sum + $i;
$add_i = true;
}

if($add_i)
{
print "$i";
if($i < (1000-LOWEST_DIVISOR))
{
print " + ";
}
else
{
print "

\n";
}
}
$i++;
}
print "sum: $sum";

?>


Follow

Get every new post delivered to your Inbox.