Objective
Today, we’re learning and practicing an algorithmic concept called Recursion.

Recursive Method for Calculating Factorial

factorial(N) = 1                                                N=1

factorial(N)=factorial(N-1)*N                       N>1

Task
Write a factorial function that takes a positive integer, N as a parameter and prints the result of N! ( N factorial).

Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of 0.

Input Format

A single integer, N (the argument to pass to factorial).

Constraints

  • 2<= N <= 12
  • Your submission must contain a recursive function named factorial.
    Output Format

Print a single integer denoting N!.

Sample Input
3
Sample Output
6

Solution:

Since it is required to use recursion method to solve this problem we must use the same. Recursion is the method of calling the method in itself.

To tackle this problem we first define the factorial function. We get most of the hint on how to develop this function from the problem itself. Recursive method of factorial is given as:

1 if the number passed to the function factorial is also 1
factorial(n-1)*n  if the number is greater than 1

Here we are also provided with the information that the value of the input n is between 2 and 12, both inclusive. So we can safely say that the input is always positive.

After defining the factorial function we must call factorial in itself. So in the return statement, we use a single line if else condition which states that return 1 if n is equal to 1 else return factorial(n-1)*n (recursive function i.e the function is called in itself).

For example, if the number n = 3, then the:

1. else statement will process which gives factorial(2)*3 as return
2. then again else statement will process which will give (factorial(1)*2)*3 as return
3. since now the factorial function has 1 as input value it will return 1
4. so the number which is returned is 1*2*3 which is equal to 6.

Solution :

import sys
 
def factorial(n):
    # Complete this function
    return 1 if n==1 else factorial(n-1)*n
 
if __name__ == "__main__":
 
    n = int(input().strip())
    result = factorial(n)
    print(result)

Day 9: Recursion HackerRank 30 Days of Code Challenge Solution

Leave a Reply

Your email address will not be published.