Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Fibonacci Sequence

Tags:

php

for-loop

This php method is suppose to print the Fibonacci sequence up to a specified value using a for loop. I am unsure why it does not work?

<?php
function fib ($n) { // a function called fib, declaire variable n (the sequence number)
    for ($n=0;$n<30;$n++) {
        if ($n < 3) { return $n; } // if n is smaller than 3 return n (1 or 2)
        else { return fib ($n - 1) + fib ($n - 2); } 
    /* if the number is 3 or above do 2 sums (n-1) and (n-2)
    and then add the 2 sums together (n-1)+(n-2)
    Example Fibonacci number 4
    (4-1)+(4-2) = 5
    3 + 2 = 5
    */
}
print $n;
?>
like image 913
Jesse Luke Orange Avatar asked Mar 24 '13 15:03

Jesse Luke Orange


2 Answers

There is actually a way to calculate a Fibonacci number without iteration by using rounding:

http://en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding

function getFib($n)
{
    return round(pow((sqrt(5)+1)/2, $n) / sqrt(5));
}
like image 68
Lee Davis Avatar answered Sep 17 '22 14:09

Lee Davis


Simple function of fibonacci

function fibonacci($n,$first = 0,$second = 1)
{
    $fib = [$first,$second];
    for($i=1;$i<$n;$i++)
    {
        $fib[] = $fib[$i]+$fib[$i-1];
    }
    return $fib;
}
echo "<pre>";
print_r(fibonacci(50));
like image 42
user2669208 Avatar answered Sep 20 '22 14:09

user2669208