fibonacci series


See On Github

Data

Contributor

Generic placeholder thumbnail

by mitogh

in php

Tags

recursion

Source Code

<?php
/**
 * Fibonnaci implementation on a recursive way, using the
 * ternary operation to apply the condition
 *
 * @param   int     $n  The number of the secuence 0 to n
 */
function fibonacci($n = 0){
    return ($n < 2) ? $n : (fibonacci($n-1) + fibonacci($n-2));
}

/**
 * Iterative implementation of the fibonacci series 
 * Use a for loop to iterate until the value of the serie
 *
 * @param   int     $n  The number of the secuence 0 to n
 */
function fibonacci_iterative($n = 0){
    $i = 1; 
    $j = 0; 
    for($k = 0; $k < $n; $k++){
        $t = $i + $j; 
        $i = $j;
        $j = $t; 
    }
    return $j;
}
<?php
require 'fibonacci.php';

class FibonacciTest extends PHPUnit_Framework_TestCase{
    public function testCeroFibonacci(){
        $this->assertEquals(fibonacci(0), 0);
        $this->assertEquals(fibonacci_iterative(0), 0);
    }
    public function testPositiveNumberFibonnacci(){
        // Given the next order
        // Keys     [0..14]
        // Values   [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377]
        $this->assertEquals(fibonacci(14), 377);
        $this->assertEquals(fibonacci_iterative(14), 377);
    }
}