Factorial of a number in Python – Coderbyte Solution

First Factorial

Factorial of a number in Python

Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it. For example: if num = 4, then your program should return (4 * 3 * 2 * 1) = 24.

For the test cases, the range will be between 1 and 18 and the input will always be an integer.

Examples

Input: 4
Output: 24

Input: 8
Output: 40320

Code:

Method1:

#Using Recursion
def FirstFactorial(num):
  # code goes here
  if num==1:
    return 1
  else:
    return num * FirstFactorial(num-1)
  
       
# keep this function call here 
print(FirstFactorial(input()))

This solution utilizes recursion to calculate the factorial of a given number (num). Here’s how it works:

  1. The FirstFactorial function is defined, which takes a single parameter num.
  2. Inside the function:
    • The base case is checked: if num is equal to 1, then the factorial of 1 is 1, so the function returns 1.
    • If the base case is not met (i.e., num is not 1), the function recursively calls itself with the argument num-1.
    • Each recursive call decrements num by 1 until it reaches the base case (num equals 1).
  3. When the base case is reached (num equals 1), the function starts returning values back up the call stack, multiplying num with the result of the recursive call (i.e., num * FirstFactorial(num-1)).
  4. Finally, the result of the outermost function call (i.e., the factorial of the original input number) is printed.

Method2:

def FirstFactorial(num):
  # code goes here
  f=1
  for i in range(1,num+1):
    f=f*i
  return f
# keep this function call here 
print(FirstFactorial(input()))


This solution computes the factorial of a given number num using a simple iterative approach. Here’s how it works:

  1. The FirstFactorial function is defined, which takes a single parameter num.
  2. Inside the function:
    • A variable f is initialized to 1. This variable will hold the factorial value.
    • A for loop iterates from 1 to num (inclusive). For each iteration:
      • The value of f is updated by multiplying it with the current value of i.
    • After the loop completes, the final value of f represents the factorial of num.
  3. The computed factorial value f is then returned by the function.
  4. The function is called with input(), which takes user input from the console. However, note that input() returns a string, so the input should be cast to an integer for the function to work correctly.
  5. Finally, the result of the FirstFactorial function call is printed.

Leave a Comment