Calculate Factorial various languages
C#
- Classic recursive
public static int CalculateFactorialRecursive(int number)
{
return number == 0 ? 1 : number * CalculateFactorialRecursive(number - 1);
}
- Iterative
public static int CalculateFactorial(int number)
{
return number == 0 ? 1 : Enumerable.Range(1, number).Aggregate(1, (current, i) => current * i);
}
Python
def calculate_factorial(input_number: int, recursive: bool = False) -> int | None:
if input_number == 0:
return 1
if recursive:
return input_number * calculate_factorial(input_number - 1, True)
result = input_number
while input_number > 1:
result *= input_number - 1
input_number -= 1
return result
Combines the two above to do both options by passing optional field of recursive boolean
JavaScript
JavaScript will do tail call optimization for this making it more efficient
function calculate_factorial(input_number, recursive) {
if (input_number === 0) {
return 1;
}
if (recursive) {
return input_number * calculate_factorial(input_number - 1, true)
}
result = input_number
while (input_number > 1) {
result *= input_number - 1
input_number -= 1
}
return result;
}