factorial 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: complexity analysis of factorial using recursion

T(n) = T(n-1) + 3   (3 is for As we have to do three constant operations like 
                 multiplication,subtraction and checking the value of n in each recursive 
                 call)

     = T(n-2) + 6  (Second recursive call)
     = T(n-3) + 9  (Third recursive call)
     .
     .
     .
     .
     = T(n-k) + 3k
     till, k = n

     Then,

     = T(n-n) + 3n
     = T(0) + 3n
     = 1 + 3n

Example 3: 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