Factorial
Definition​
- Definition
- Explanation
- Guidance
- Tips
The Factorial Algorithm is a mathematical procedure used to calculate the factorial of a non-negative integer
The factorial of a non-negative integer n
, denoted as n!
, is the product of all positive integers less than or equal to n
. It's often expressed recursively or iteratively
- Start with a non-negative integer input
n
- If
n
is0
or1
, return1
(base case) - Otherwise, recursively multiply
n
by the factorial of (n-1
) until reaching the base case - Return the final result
- for small inputs (typically less than 12), consider using an iterative approach for efficiency
- optimize for tail recursion if using a recursive approach to prevent stack overflow errors
- use memoization technique to reduce the computation time and improve the performance
Practice​
- Practice
- Solution
factorial(n):
if n is negative:
throw "Invalid input: Cannot compute factorial of a negative number"
else if n equals 0 or 1:
return 1
else:
return n * factorial(n - 1)
package main
// recursive
func factorialRecursive(n int) int {
if n <= 1 {
return 1
}
return n * factorialRecursive(n-1)
}
// iterative
func factorialIterative(n int) int {
result := 1
for i := 2; i <= n; i++ {
result *= i
}
return result
}
public class Main {
// recursive
public static int factorialRecursive(int n) {
if (n <= 1) {
return 1;
}
return n * factorialRecursive(n - 1);
}
// iterative
public static int factorialIterative(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
}
// recursive
function factorialRecursive(n) {
if (n <= 1) {
return 1;
}
return n * factorialRecursive(n - 1);
}
// iterative
function factorialIterative(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// recursive
fun factorialRecursive(n: Int): Int {
return if (n <= 1) 1 else n * factorialRecursive(n - 1)
}
// iterative
fun factorialIterative(n: Int): Int {
var result = 1
for (i in 2..n) {
result *= i
}
return result
}
=
# recursive
def factorial_recursive(n):
return 1 if n <= 1 else n * factorial_recursive(n - 1)
# iterative
def factorial_iterative(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
// recursive
fn factorial_recursive(n: u64) -> u64 {
if n <= 1 {
1
} else {
n * factorial_recursive(n - 1)
}
}
// iterative
fn factorial_iterative(n: u64) -> u64 {
let mut result = 1;
for i in 2..=n {
result *= i;
}
result
}
// recursive
function factorialRecursive(n: number): number {
return n <= 1 ? 1 : n * factorialRecursive(n - 1);
}
// iterative
function factorialIterative(n: number): number {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}