factorial using recursion code example

Example 1: factorial of a number using recursion in python

# Factorial of a number using recursion

def recur_factorial(n):
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)

num = 7

# check if the number is negative
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   print("The factorial of", num, "is", recur_factorial(num))

Example 2: find factoril in C using recursion

#include
fact(int i, int k){
    k=k*i;
    i--;
    if(i==0){
        return k;
    }
    else{
        fact(i, k);
    }
}
int main()
{
    int k = 1, i, factorial;
    scanf("%d",&i);
    factorial = fact(i, k);
    printf("%d\n",factorial);
    return 0;
}

Example 3: c++ factorial

#include 

int fact(int n){
    return std::tgamma(n + 1);  
}    
// for n = 5 -> 5 * 4 * 3 * 2 = 120 
//tgamma performas factorial with n - 1 -> hence we use n + 1

Example 4: recursion factorial algorithm

FUNCTION FACTORIAL (N: INTEGER): INTEGER
(* RECURSIVE COMPUTATION OF N FACTORIAL *)

BEGIN
  (* TEST FOR STOPPING STATE *)
  IF N <= 0 THEN
    FACTORIAL := 1
  ELSE
    FACTORIAL := N * FACTORIAL(N - 1)
END; (* FACTORIAL *)

Tags:

Misc Example