Starter with the logic implementation through programming so please find my honest efforts for project Euler Ques, although i tried various attempts to solve but could not get through it 🙁
Sum I am getting from this is – 257112. I added +2 in the sum to count for a[1] = 2 in the series, but its not working, also I am currently passing a static value 45 for $num but i think it is not the correct way, let me know where I am lagging in logic for the 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.
this is the code I tried –>
$a = array();
$a[0] = 1; $a[1] = 2; $num = 45; $i= 0; $sum = 0; $stop = $num -2;
for($i; $i < $stop ; $i++ ) {
$a[$i+2] = $a[$i+1] + $a[$i];
if( $a[$i+2]%2 == 0 && $a[$i+2] <= 400000 )
{
$sum += $a[$i+2];
}
}
echo "<pre>";
print_r($a);
echo "<br>"."Sum is : ".$sum;
EDIT – It was an error to add an extra zero to make it 4 million, although I am looking something for $num not to be static (as 45 I just mentioned randomly, although its working but its not a clean solution)
Make it simple, no arrays and make it quick. You are only looking for the sum, nothing else:
If 4,000,000 counted, then it would be
$b<=4000000