HackerRank Day 9 Solution in Python: Recursion

Today we will see the HackerRank Day 9 Solution in Python. The problem is named Recursion which is part of 30 Days of code on HackerRank. Let’s get started!

Day 9: Recursion Problem statement

We have to write the logic for factorial using recursion in the factorial function

Sample Input


Sample Output


Explanation: The factorial of 3 is 6(3*2*1)

You can solve the problem here.

HackerRank Day 9 Solution in Python


import math
import os
import random
import re
import sys

# Function to find the factorial 
def factorial(n):
    if (n==1):
        return n
        return n*factorial(n-1)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')
    n = int(input())
    result = factorial(n)
    fptr.write(str(result) + '\n')

Code Explanation

  • First, get the input from the user
  • Then in the factorial function write the logic to find the factorial using recursion
  • That is if the number is n, then return 1
  • Else recursively call the function by n*factorail(n-1) to get the factorial of the given number

Also Read:


Author: Ayush Purawr