Euler’s Prob.2 – PHP Program to find the sum of the even-valued terms in the Fibonacci

PHP script for the Euler’s Problem 2.

Question:

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.

Solution for the above problem solved in PHP:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$sum = 0;
$first = 1;
$second = 2;
echo "<b>EVEN Values from Fibonacci Series </b><br />";
//check if the second value is less than 4 million
while ($second < 4000000)
{
//check whether the value is odd or even
if($second % 2 == 0)
{
$sum += $second;
echo $second."<br>";
}
//keep the first value in a temporary variable
$tmp = $first;
//assign the second value to first
$first = $second;
//add the temp value and second
$second = $tmp + $second;
}
//display the final value
echo "<br /><b>TOTAL: </b>". $sum;
?>
<?php $sum = 0; $first = 1; $second = 2; echo "<b>EVEN Values from Fibonacci Series </b><br />"; //check if the second value is less than 4 million while ($second < 4000000) { //check whether the value is odd or even if($second % 2 == 0) { $sum += $second; echo $second."<br>"; } //keep the first value in a temporary variable $tmp = $first; //assign the second value to first $first = $second; //add the temp value and second $second = $tmp + $second; } //display the final value echo "<br /><b>TOTAL: </b>". $sum; ?>
<?php

$sum        =     0;
$first         =     1;
$second        =      2;
echo "<b>EVEN Values from Fibonacci Series </b><br />";

//check if the second value is less than 4 million
while ($second < 4000000)
{
//check whether the value is odd or even
if($second % 2 == 0)
{
$sum += $second;
echo $second."<br>";
}

//keep the first value in a temporary variable
$tmp      = $first;
//assign the second value to first
$first   = $second;
//add the temp value and second
$second     = $tmp + $second;
}
//display the final value
echo "<br /><b>TOTAL: </b>". $sum;

?>

How the code works is explained in the above code itself. Hope you Enjoy!

 

Leave a Reply

Theme: Overlay by Kaira
Agurchand