factorial


See On Github

Data

Contributor

Generic placeholder thumbnail

by mitogh

in php

Source Code

<?php
/**
 * Factorial in a recursive way
 * for convention 0! = 1
 * 
 * @param   int     $n  Factorial of $n
 */
function factorial($n = 0){
    return ($n <= 0) ? 1 : ($n * factorial($n-1));
}

/**
 * Factorial implemented in trought a while
 * loop. 
 *
 * @param   int     $n  Factorial of $n
 */
function factorial_iterative($n = 0){
    $factorial = 1; 
    if(!$n){
        return $factorial;
    }

    while($n){
        $factorial *= $n--;
    }
    return $factorial;
}
<?php
require 'factorial.php';

class Factorial extends PHPUnit_Framework_TestCase{
    public function testZeroFactorial(){
        $this->assertEquals(factorial(0), 1);
        $this->assertEquals(factorial_iterative(0), 1);
    }
    public function testNormalFactorial(){
        $this->assertEquals(factorial(5), 120);
        $this->assertEquals(factorial_iterative(5), 120);
    }
    public function testNoParamsFactorial(){
        $this->assertEquals(factorial(), 1);
        $this->assertEquals(factorial_iterative(), 1);
    }
    public function testBothFunctions(){
        $this->assertEquals(factorial(10), factorial_iterative(10));
    }
}