calculate static method
Calculates the factorial of a non-negative integer n using an iterative approach.
The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
Definition:
- 0! = 1
- n! = n * (n-1) * (n-2) * ... * 1 for n > 0
Parameters:
n: The non-negative integer for which to calculate the factorial.
Returns:
A BigInt representing the factorial of n.
Throws:
- ArgumentError: If
nis a negative number.
Implementation
static BigInt calculate(int n) {
if (n < 0) {
throw ArgumentError('Factorial is not defined for negative numbers.');
}
if (n == 0) {
return BigInt.one;
}
var result = BigInt.one;
for (int i = 1; i <= n; i++) {
result *= BigInt.from(i);
}
return result;
}