Logo

Programming-Idioms

  • Ada
  • Php

Idiom #31 Recursive factorial (simple)

Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)

function f(int $i): int
{
    if ($i == 0) {
        return 1;
    }

    return $i * f($i - 1);
}
function f($i) {
	if($i == 0) {
		return 1;
	}

	return ($i * f($i-1));
}
function F (I : Natural) return Natural is (if I < 2 then 1 else I * F (I - 1));
unsigned int f(unsigned int i)
{
	return i?i*f(i-1):1;
}

Overflows for i>20 in 64bits and for i>12 in 32bits

New implementation...
< >
programming-idioms.org