878913. Factorial
Factorial
Slug: factorial-1598335080--125944 Difficulty: Basic Id: 878913 Topic Tags: python-loops, CPP, Java
Summary
The problem of finding the factorial of a given integer is a basic algorithmic problem. The key concept involved is recursion or iterative approach to calculate the factorial of a number. Factorial of a number n is denoted by n! and it is calculated as the product of all positive integers less than or equal to n.
Detailed Explanation
The simplest way to calculate the factorial of a given integer is using an iterative approach with a loop. The idea is to initialize a variable result to 1, then for each number from 2 to the input number, multiply result by that number. This process continues until the input number becomes 0.
Here's a step-by-step breakdown of the solution:
- Initialize a variable
resultto 1. - Start a loop from 2 to the input number (inclusive).
- In each iteration of the loop, multiply
resultby the current number. - After the loop finishes,
resultwill be the factorial of the input number.
The time complexity of this algorithm is O(n), where n is the input number. The space complexity is O(1) as we are only using a constant amount of space to store the result.
Optimized Solutions
Java
public class Factorial {
public static long factorial(int n) {
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
}