"Python/SageMath's [unlimited precision integers](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) make this trivial."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "abf93cda",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4075"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"binoms = (binomial(n, r) for n in range(1, 101) for r in range(0, n + 1))\n",
"len([b for b in binoms if b > 1000000])"
]
},
{
"cell_type": "markdown",
"id": "6d7f4409",
"metadata": {},
"source": [
"If it weren't for unlimited precision, we would have a problem, since a lot of these [binomial coefficients](https://en.wikipedia.org/wiki/Binomial_coefficient) overflow a 64 bit integer - the largest one we encounter here is $\\binom{100}{50} = 100891344545564193334812497256$.\n",
"\n",
"However, even in that case there's a pretty simple workaround: finding $n$ and $r$ such that\n",
"$$\\binom{n}{r} > 1000000$$\n",
"is the same as finding $n$ and $r$ such that\n",
"$$\\log{\\binom{n}{r}} > \\log{1000000}$$\n",
"By applying the definition of the binomial coefficients and [logarithmic identities](https://en.wikipedia.org/wiki/List_of_logarithmic_identities), this turns to\n",
"$\\log{100!} \\approx 363.739$, nowhere close to overflowing a float.\n",
"\n",
"$\\log{n!}$ can be computed in a number of ways. You can use the [log-gamma function](https://en.wikipedia.org/wiki/Gamma_function), or you can implement a function yourself, either by applying logarithmic identities again:\n",
"$$\\log{n!} \\approx \\left(n + \\frac{1}{2}\\right)\\log{n} - n + \\frac{1}{2}\\log{2\\pi}$$\n",
"\n",
"#### Copyright (C) 2025 filifa\n",
"\n",
"This work is licensed under the [Creative Commons Attribution-ShareAlike 4.0 International license](https://creativecommons.org/licenses/by-sa/4.0/) and the [BSD Zero Clause license](https://spdx.org/licenses/0BSD.html)."