Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save rmamont/cee1424773432bebc5d9f52d09b5e2a6 to your computer and use it in GitHub Desktop.

Select an option

Save rmamont/cee1424773432bebc5d9f52d09b5e2a6 to your computer and use it in GitHub Desktop.

Revisions

  1. rmamont created this gist May 3, 2017.
    46 changes: 46 additions & 0 deletions Factorial in recursive and iterative methods
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    <?php
    function factorial_recursive($num)
    {
    if ($num < 0) {
    return 'Param must be larger than zero!!';
    }

    if ($num < 2) {
    return $num;
    }

    return factorial_recursive($num - 1) * $num;
    }

    assert('Param must be larger than zero!!' == factorial_recursive(-5));
    assert(0 == factorial_recursive(0));
    assert(1 == factorial_recursive(1));
    assert(120 == factorial_recursive(5));
    assert(24 == factorial_recursive(4));

    function factorial_iterative($num)
    {
    $iter = function($num, $acc) use (&$iter) {
    if ($num < 0) {
    return 'Param must be larger than zero!!';
    }

    if ($num == 0) {
    return 0;
    }

    if ($num == 1) {
    return $acc;
    }

    return $iter($num - 1, $acc * $num);
    };

    return $iter($num, 1);
    }

    assert('Param must be larger than zero!!' == factorial_iterative(-5));
    assert(0 == factorial_iterative(0));
    assert(1 == factorial_iterative(1));
    assert(120 == factorial_iterative(5));
    assert(24 == factorial_iterative(4));