Day 9 - Recursion

November 08, 2017


Objective

Today, we’re learning and practicing an algorithmic concept called Recursion. Check out the Tutorial tab for learning materials and an instructional video!

Recursive Method for Calculating Factorial

Task

Write a factorial function that takes a positive integer, as a parameter and prints the result of ( 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, (the argument to pass to factorial).

Constraints

Your submission must contain a recursive function named factorial.

Output Format

Print a single integer denoting .

Sample Input

3

Sample Output

6

Explanation

Consider the following steps:

From steps 2 and 3, we can say ; then when we apply the value from to step 1, we get . Thus, we print 6 as our answer.

1
2
3
4
5
6
7
8
9
10
11
12
13
import sys

def factorial(n):
    # Complete this function
    if n > 1:
        return n * factorial(n - 1)
    else:
        return 1

if __name__ == "__main__":
    n = int(input().strip())
    result = factorial(n)
    print(str(result))