BASHA TECH
[HackerRank][Python] Recursion 3 본문
728x90
Recursive Method for Calculating Factorial
factorial(N) = 1 : N <= 1 , N x factorial (N - 1) : otherwise
Function Description
Complete the factorial function in the editor below. Be sure to use recursion.
factorial has the following paramter:
- int n: an integer
Returns
- int: the factorial of n
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.
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'factorial' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER n as parameter.
#
def factorial(n):
# Write your code here
if n <= 1 :
return 1
else :
return n * factorial(n-1)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
result = factorial(n)
fptr.write(str(result) + '\n')
fptr.close()
This implementation uses the recursive formula for calculating the factorial of a number. If the input n is less than or equal to 1, then the function returns 1. Otherwise, it calculates n * factorial(n-1) by calling the factorial function recursively with the argument n-1.
728x90
반응형
'Activity > Coding Test' 카테고리의 다른 글
[HackerRank][Python] 2D Arrays (0) | 2023.04.24 |
---|---|
[HackerRank][Python] Binary Numbers (0) | 2023.04.17 |
[HackerRank][Python] Dictionaries and Maps (0) | 2023.04.17 |
[HackerRank][Python] Arrays (0) | 2023.04.17 |
[HackerRank][Python] Let's Review (1) | 2023.04.17 |
Comments