I’m trying to understand a specific pattern where each term is the sum of the previous term and the current Fibonacci number. The pattern follows this sequence:
1
1 + 1 = 2
1 + 1 + 2 = 4
1 + 1 + 2 + 3 = 7
1 + 1 + 2 + 3 + 5 = 12
And so on
I would like to create a function in PHP that generates this pattern. I have attempted to modify a standard Fibonacci function, but the results are not as expected. Here’s the code I’ve tried so far:
function getResult($n) {
$result = [];
$previous = 0;
$current = 1;
for ($i = 1; $i <= $n; $i++) {
$result[] = $current;
$previous = $current;
$next = $previous + $current;
$current = $next;
}
return $result;
}
2
Answers
Put
$previous = $current;
after$next = $previous + $current;
Live JavaScript snippet just to illustrate the result:
Update: Or did you mean you want to generate the sequence
1 2 4 7 12 20 33
?Then this is basically
Sn = Fn+2-1
:For Fibonacci Sequent (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144…..), you may use the following PHP code to get:
So, for your case which you want to get the sum of the previous terms and the current Fibonacci number (1 2 4 7 12 20 33 54 88 143 …), you can use the following:
See DEMO