Fibonacci Sequence Php Practice_PHP Tutorial

WBOY
Release: 2016-07-14 10:12:08
Original
938 people have browsed it

The sequence starts with the third term, and each term is equal to the sum of the previous two terms.


F0=0, F1=1, Fn=F(n-1)+F(n-2)


Recursive version and non-recursive version.


php 
function fib($n){ 
    $array = array(); 
    $array[0] = 1; 
    $array[1] = 1; 
    for($i=2;$i<$n;$i++){ 
        $array[$i] = $array[$i-1]+$array[$i-2]; 
    } 
    print_r($array); 
} 
fib(10); 
echo "\n------------------\n"; 
function fib_recursive($n){ 
    if($n==1||$n==2){return 1;} 
    else{ 
        return fib_recursive($n-1)+fib_recursive($n-2); 
    } 
} 
echo fib_recursive(10); 
?> 

<?php
function fib($n){
 $array = array();
 $array[0] = 1;
 $array[1] = 1;
 for($i=2;$i<$n;$i++){
  $array[$i] = $array[$i-1]+$array[$i-2];
 }
 print_r($array);
}
fib(10);
echo "\n------------------\n";
function fib_recursive($n){
 if($n==1||$n==2){return 1;}
 else{
  return fib_recursive($n-1)+fib_recursive($n-2);
 }
}
echo fib_recursive(10);
?>

Copy after login

As a C and Java programmer, the first time I wrote non-recursive code, I forgot to add $ in front of the variables, which was tragic.

Output results

Array 
( 
    [0] => 1 
    [1] => 1 
    [2] => 2 
    [3] => 3 
    [4] => 5 
    [5] => 8 
    [6] => 13 
    [7] => 21 
    [8] => 34 
    [9] => 55 
) 
 
------------------ 
55 

Array
(
    [0] => 1
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 5
    [5] => 8
    [6] => 13
    [7] => 21
    [8] => 34
    [9] => 55
)

------------------
55
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477237.htmlTechArticleThe sequence starts with the third term, and each term is equal to the sum of the previous two terms. F0=0, F1=1, Fn=F(n-1)+F(n-2) recursive version and non-recursive version. php function fib($n){ $array = array(); $array[0] = 1; $a...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template