Given a number num, write a Python program to find the factorial of that number. The Factorial of a non-negative number is equal to the multiplication of all integers smaller than or equal to that number.
Example: Input: num = 5 Output: 120 Explanation: 5*4*3*2*1 = 120 Input: num = 0 Output: 1 Input: num = 7 Output: 5040 Explanation: 7*6*5*4*3*2*1 = 5040
Approach 1: Factorial of a number using a for a loop.
In this approach, the program uses a for loop to iterate through the numbers from 1 to the given number and calculates the factorial by multiplying each number.
Python Code:
# take input for the number num = int(input("Enter a number: ")) # initialize the factorial to 1 factorial = 1 # use a for loop to calculate the factorial for i in range(1, num + 1): factorial *= i # print the result print("The factorial of", num, "is", factorial)
Enter a number: 5
The factorial of 5 is 120
- Time Complexity: O(n)
- Space Complexity: O(1)
Approach 2: Factorial of a number using Recursion.
In this approach, the program uses recursion to find the factorial. The factorial function calls itself with the argument n-1 until the base case n=1 is reached, and then returns the result.
Python Code:
# define a recursive function to find the factorial def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) # take input for the number num = int(input("Enter a number: ")) # call the factorial function to find the factorial result = factorial(num) # print the result print("The factorial of", num, "is", result)
Output:
Enter a number: 5
The factorial of 5 is 120
- Time Complexity: O(n)
- Space Complexity: O(n)
Approach 3: Factorial of a number using a While loop.
In this approach, the program uses a while loop to calculate the factorial in a similar way as the for loop in approach 1.
Python Code:
# take input for the number num = int(input("Enter a number: ")) # initialize the factorial to 1 factorial = 1 # initialize the counter to 1 i = 1 # use a while loop to calculate the factorial while i <= num: factorial *= i i += 1 # print the result print("The factorial of", num, "is", factorial)
Output:
Enter a number: 7
The factorial of 7 is 5040
- Time Complexity: O(n)
- Space Complexity: O(1)
Related Articles:
No comments:
Post a Comment