Faced such a task:
Each new element of the Fibonacci sequence is obtained by adding the previous two. Starting from 1 and 2, we get the first 10 elements: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of all even elements of the Fibonacci sequence whose sequence number is less than A and return the sum from the function all its numbers.
Example: A = 10
Fibonacci series: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
Even elements: 2, 8, 34
Their sum: 44, and the sum of all its numbers - 8.
It seemed easy and began to solve this way:
<?php function solution($X) { $arr = array(1, 2); $sum = 0; $len = 0; for ($i = 2; $i <= $X; $i++) { array_push($arr, $arr[$i - 1] + $arr[$i - 2]); if ((($arr[$i - 1]) % 2) == 0 && ($i - 1) < $X) { $sum += $arr[$i - 1]; } } while ($sum != 0 && $sum > 0) { $len += $sum % 10; $sum = intval($sum / 10); } return $len; } print solution(10);
If during the check you specify 10 ( solution(10)
), then the answer is correct, if you specify a number that is greater than 90, then the answer is always 0.
The question itself is this. Where am I wrong?