In project Euler example 2 the question is very simple:
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.
Now to find a Fibonacci sequence
function fabonnaciNumber()
{
$a = 1;
$b = 1;
$sum = 0;
$c = $a + $b;
while($c < 4000000){
if($c % 2 == 0){
$sum += $c; // $sum = $sum + $c;
$a = $b + $c;
$b = $a + $c;
$c = $a + $b;
}
}
echo $sum;
}
echo fabonnaciNumber();
In this function, the variable $a is initialized with value 1 and $b is also initialized with the value 1. We need to store the sum and make sure the value is not exceeding 4000000. so we have to create a new variable called $sum initialized with value 0. Create another variable called $c = $a + $b; which holds the sum value of $a and $b.\
Now run a while loop that has a maximum iteration value of 4000000. check if the number is perfectly divisible by 2 then sum the value of $c into $sum and update the value of $a, $b, and $c.