calculateDouble static method
Calculates the double factorial (n!!) of an integer n using an iterative approach.
The double factorial is the product of all integers from 1 up to n that have the same parity (odd or even) as n.
Definition:
- If n is even: n!! = n * (n-2) * (n-4) * ... * 2
- If n is odd: n!! = n * (n-2) * (n-4) * ... * 1
- 0!! = 1
- (-1)!! = 1 (by convention, for consistency with Gamma function relations)
Parameters:
n: The integer for which to calculate the double factorial.
Returns:
A BigInt representing the double factorial of n.
Throws:
- ArgumentError: If
nis a negative number less than -1.
Implementation
static BigInt calculateDouble(int n) {
if (n < -1) {
throw ArgumentError(
'Double factorial is not defined for numbers less than -1.',
);
}
if (n == 0 || n == -1) {
return BigInt.one;
}
var result = BigInt.one;
for (int i = n; i >= 1; i -= 2) {
result *= BigInt.from(i);
}
return result;
}