Home > php教程 > php手册 > 斐波那契数列 Php练手

斐波那契数列 Php练手

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-13 10:58:07
Original
1157 people have browsed it

    数列从第三项开始,每一项都等于前两项之和。


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


       递归版和非递归版。


 

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

作为C和java的程序猿,在第一次在写非递归的时候,忘记了变量前加$,悲催。

输出结果

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

 

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template