Day 2 - Python

Problem Statement (Factorial - Iterative and Recursive)

You are given a non-negative integer N. Your task is to compute the factorial of N. You are required to implement both an iterative and a recursive approach, and depending on user input, the appropriate function should be called.

Write two functions:

factorial_iterative(N): This function should compute the factorial of N using an iterative approach.

factorial_recursive(N): This function should compute the factorial of N using a recursive approach.

You need to implement a main function compute_factorial(N, method) that takes the following parameters:

N: an integer (0 ≤ N ≤ 100) representing the number whose factorial needs to be computed.

method: an integer indicating the method to be used for computation. If method is 1, it should call the iterative function, if method is 2, it should call the recursive function.

The main function should call the appropriate factorial function based on the method parameter and return the computed factorial.

Test Cases

Input:

7

1

Output:

5040

Input:

100

2

Output:

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Input:

1

3

Output:

-1


SOLUTION

def factorial_iterative(N):

    if N == 0 or N == 1:

        return 1

    factorial = 1

    for i in range(2, N+1):

        factorial *= i

    return factorial


def factorial_recursive(N):

    if N == 0 or N == 1:

        return 1

    return N * factorial_recursive(N-1)


def compute_factorial(N, method):

    if method == 1:

        return factorial_iterative(N)

    elif method == 2:

        return factorial_recursive(N)

    else:

        return -1


N = int(input())

method = int(input())

print(compute_factorial(N, method))


Insights

  • Explore what is recursion and what error occurs if the input value is too high.
  • Check for the invalid cases based on the methods and also number for which the factorial has to be calculated.
  • Compare and contrast the differences between the two methods.
  • Try incorporating the exception handling technique for this problem.
  • Explore what is MEMOIZATION! Let's use that soon with another recursive problem! 
Recursion is like using a special mirror. You break a problem into smaller parts, solve each part with the mirror, and then put the solutions together until you have the answer.

Similarly, make your coding journey also like a enthusiastic roller coaster ride exploring new nuances! 

Keep smiling and happy Coding! :)

Comments