/*
binomialCoefficient($n, $k):
Computes "n choose k" using the multiplicative formula:
C(n, k) = product(i = 1..k) of (n - k + i) / i
Why this method?
- Avoids huge factorials (37! is far too large for PHP integers)
- Keeps intermediate values small and exact
- Efficient, clean, and idiomatic in PHP
Returns:
The binomial coefficient as an integer.
*/
function binomialCoefficient(int $n, int $k): int
{
if ($k > $n) {
return 0;
}
// Use symmetry: C(n, k) == C(n, n-k)
if ($k > $n - $k) {
$k = $n - $k;
}
$result = 1;
for ($i = 1; $i <= $k; $i++) {
$result = intdiv($result * ($n - $k + $i), $i);
}
return $result;
}
/* Main program */
$mainN = 37;
$mainK = 6;
$powerN = 7;
$powerK = 1;
$mainCombos = binomialCoefficient($mainN, $mainK);
$powerCombos = binomialCoefficient($powerN, $powerK);
$total = $mainCombos * $powerCombos;
echo "Main combinations (C(37,6)): $mainCombos\n";
echo "Power combinations (C(7,1)): $powerCombos\n";
echo "Total lottery combinations: $total\n";
/*
run:
Main combinations (C(37,6)): 2324784
Power combinations (C(7,1)): 7
Total lottery combinations: 16273488
*/