Home  >  Article  >  Backend Development  >  How to implement Fibonacci sequence in php

How to implement Fibonacci sequence in php

hzc
hzcOriginal
2020-06-10 16:10:202867browse

How to implement Fibonacci sequence in php

php implements Fibonacci sequence

Fibonacci sequence:
1 1 2 3 5 8 13 21 34 55…

Concept:
The first two values ​​​​are both 1. The sequence starts from the third digit, and each digit is the sum of the first two digits of the current digit.
The regular formula is:
Fn = F(n- 1) F(n 1)
F: refers to the current sequence
n: the subscript of the exponential sequence

Non-recursive writing:

function fbnq($n){  //传入数列中数字的个数
    if($n <= 0){
        return 0;
    }
    $array[1] = $array[2] = 1; //设第一个值和第二个值为1
    for($i=3;$i<=$n;$i++){ //从第三个值开始
        $array[$i] = $array[$i-1] + $array[$i-2]; 
        //后面的值都是当前值的前一个值加上前两个值的和
    }
    return $array;
}

Recursive writing:

function fbnq($n){    
    if($n <= 0) return 0; 
    if($n == 1 || $n == 2) return 1; 
    return fbnq($n - 1) + fbnq($n - 2);
}

Recommended tutorial: "php tutorial"

The above is the detailed content of How to implement Fibonacci sequence in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn