You are given an integer n. Return the value of n! or n factorial.
Factorial of a number is the product of all positive integers less than or equal to that number.
Input: n = 2
Output: 2
Explanation: 2! = 1 * 2 = 2.
Input: n = 0
Output: 1
Explanation: 0! is defined as 1.
Input: 3
Given a number, its factorial can be found by multiplying all positive integers starting from 1 to the given number.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to find the
factorial of a number*/
int factorial(int n) {
// Variable to store the factorial
int fact = 1;
// Iterate from 1 to n
for(int i = 1; i <= n; i++) {
// Multiply fact with current number
fact = fact * i;
}
// Return the factorial stored
return fact;
}
};
int main()
{
int n = 4;
/* Creating an instance of
Solution class */
Solution sol;
// Function call to find the factorial of n
int ans = sol.factorial(n);
cout << "The factorial of given number is: " << ans;
return 0;
}
class Solution {
/* Function to find the
factorial of a number */
public int factorial(int n) {
// Variable to store the factorial
int fact = 1;
// Iterate from 1 to n
for(int i = 1; i <= n; i++) {
// Multiply fact with current number
fact = fact * i;
}
// Return the factorial stored
return fact;
}
public static void main(String[] args) {
int n = 4;
/* Creating an instance of
Solution class */
Solution sol = new Solution();
// Function call to find the factorial of n
int ans = sol.factorial(n);
System.out.println("The factorial of given number is: " + ans);
}
}
class Solution:
# Function to find the
# factorial of a number
def factorial(self, n):
# Variable to store the factorial
fact = 1
# Iterate from 1 to n
for i in range(1, n + 1):
# Multiply fact with current number
fact = fact * i
# Return the factorial stored
return fact
# Input number
n = 4
# Creating an instance of Solution class
sol = Solution()
# Function call to find the factorial of n
ans = sol.factorial(n)
print("The factorial of given number is: ", ans)
class Solution {
/* Function to find the
factorial of a number */
factorial(n) {
// Variable to store the factorial
let fact = 1;
// Iterate from 1 to n
for (let i = 1; i <= n; i++) {
// Multiply fact with current number
fact = fact * i;
}
// Return the factorial stored
return fact;
}
}
// Input number
let n = 4;
// Creating an instance of Solution class
let sol = new Solution();
// Function call to find the factorial of n
let ans = sol.factorial(n);
console.log("The factorial of given number is: ", ans);
Time Complexity: O(N) – Iterating once from 1 to N.
Space Complexity: O(1) – Using a couple of variables i.e., constant space.