This language bar is your friend. Select your favorite languages!

Idiom #31 Recursive factorial (simple)

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

unsigned int f(unsigned int i)
{
	return i?i*f(i-1):1;
}
function F (I : Natural) return Natural is (if I < 2 then 1 else I * F (I - 1));
unsigned int f( unsigned int i ) {
	if ( i == 0 ) return 1;
	
	return i * f( i - 1 )
}
uint factorial(in uint n) pure nothrow @nogc
in {
    assert(n <= 12);
} body {
    if (n == 0)
        return 1;
    else
        return n * factorial(n - 1);
}
f(i) => (i == 0) ? 1 : i * f(i - 1);
defmodule Factorial do
  def of(0), do: 1
  def of(n) when n > 0 do
    n * of(n-1)
  end
end
f(0) -> 1;
f(I) -> I * f(I - 1).
func f(i int) int {
  if i == 0 {
    return 1
  }
  return i * f(i-1)
}
f i = if i > 1 then f (i-1) * i else 1
function f(n) {
   return n<2 ? 1 : n * f(n-1);
}
int f(int i){
	if(i==0)
		return 1;
	else
		return i * f(i-1);
} 
function f(n)
   local function f_(factorial,n)
      if n < 2 then return 1
      return f_(factorial*n, n-1)
   end
   return f_(1,n)
end
function f($i) {
	if($i == 0) {
		return 1;
	}
	else {
		return ($i * f($i-1));
	}
}
type
  TPositiveInt = 0..MaxInt;

function _f(_i: TPositiveInt): Integer;
begin
  if (_i < 2) then
    Result := 1
  else
    Result := _f(_i - 1);
end; 
sub f {
   my $n = shift;
   return $n<2 ? 1 : $n * f($n-1);
}
def f(i):
   if i == 0:
       return 1
   else:
       return i * f(i-1)
f = Hash.new { |hash, i| hash[i] = i * hash[i -1] }
f[0] = 1
1
fac = Hash.new {|h, i| h[i] = i * h[i-1] }.tap {|h| h[0] = 1 }
fn f(n: u32) -> u32 {
    if n < 2 {
        1
    } else {
        n * f(n - 1)
    }
}

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org