Evaluate binomial coefficients: Difference between revisions
Content added Content deleted
(Add Seed7 example) |
No edit summary |
||
Line 1,548: | Line 1,548: | ||
{{Out}} |
{{Out}} |
||
<pre><10,118264581564861424></pre> |
<pre><10,118264581564861424></pre> |
||
=={{header|Windows Batch}}== |
|||
<lang dos>@echo off & setlocal |
|||
if "%~2"=="" ( echo Usage: %~nx0 n k && goto :EOF ) |
|||
call :binom binom %~1 %~2 |
|||
1>&2 set /P "=%~1 choose %~2 = "<NUL |
|||
echo %binom% |
|||
goto :EOF |
|||
:binom <var_to_set> <N> <K> |
|||
setlocal |
|||
set /a coeff=1, nk=%~2 - %~3 + 1 |
|||
for /L %%I in (%nk%, 1, %~2) do set /a coeff *= %%I |
|||
for /L %%I in (1, 1, %~3) do set /a coeff /= %%I |
|||
endlocal && set "%~1=%coeff%" |
|||
goto :EOF</lang> |
|||
{{Out}} |
|||
<pre> |
|||
> binom.bat 5 3 |
|||
5 choose 3 = 10 |
|||
> binom.bat 100 2 |
|||
100 choose 2 = 4950 |
|||
</pre> |
|||
The string <code>n choose k = </code> is output to stderr, while the result is echoed to stdout. This should allow capturing the result with a <code>for /f</code> loop without needing to define tokens or delims. |
|||
But... |
|||
<pre> |
|||
> binom.bat 33 17 |
|||
33 choose 17 = 0 |
|||
> binom.bat 15 10 |
|||
15 choose 10 = -547 |
|||
</pre> |
|||
The Windows cmd console only handles 32-bit integers. If a factoral exceeds 2147483647 at any point, <code>set /a</code> will choke and roll over to a negative value, giving unexpected results. Unfortunately, this is as good as it gets for pure batch. It's probably better to employ a PowerShell or JScript helper or similar instead. |
|||
=={{header|XPL0}}== |
=={{header|XPL0}}== |