Evaluate binomial coefficients: Difference between revisions

m
→‎{{header|Oberon}}: Fixed language name
m (→‎{{header|Oberon}}: Fixed language name)
 
(21 intermediate revisions by 14 users not shown)
Line 18:
=={{header|11l}}==
{{trans|Python}}
<langsyntaxhighlight lang="11l">F binomial_coeff(n, k)
V result = 1
L(i) 1..k
Line 24:
R result
 
print(binomial_coeff(5, 3))</langsyntaxhighlight>
 
{{out}}
Line 34:
{{trans|ABAP}}
Very compact version.
<langsyntaxhighlight lang="360asm">* Evaluate binomial coefficients - 29/09/2015
BINOMIAL CSECT
USING BINOMIAL,R15 set base register
Line 57:
PG DS CL12 buffer
YREGS
END BINOMIAL</langsyntaxhighlight>
{{out}}
<pre>
Line 64:
 
=={{header|ABAP}}==
<langsyntaxhighlight ABAPlang="abap">CLASS lcl_binom DEFINITION CREATE PUBLIC.
 
PUBLIC SECTION.
Line 91:
ENDMETHOD.
 
ENDCLASS.</langsyntaxhighlight>
{{Out}}
<pre>lcl_binom=>calc( n = 5 k = 3 )
Line 100:
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun fac (n)
(if (zp n)
1
Line 106:
 
(defun binom (n k)
(/ (fac n) (* (fac (- n k)) (fac k)))</langsyntaxhighlight>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Binomial is
Line 137:
end loop;
end Test_Binomial;
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 170:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
 
<langsyntaxhighlight lang="algol68">PROC factorial = (INT n)INT:
(
INT result;
Line 194:
test:(
print((choose(5, 3), new line))
)</langsyntaxhighlight>
{{Out}}
<pre>
Line 201:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% calculates n!/k! %
integer procedure factorialOverFactorial( integer value n, k ) ;
Line 232:
write( binomialCoefficient( 5, 3 ) )
 
end.</langsyntaxhighlight>
 
=={{header|APL}}==
When the factorial operator <tt>!</tt> is used as a dyad, it returns the binomial coefficient: <tt>k!n</tt> = <i>n</i> choose <i>k</i>.
<syntaxhighlight lang="apl"> 3!5
10</syntaxhighlight>
=={{header|AppleScript}}==
===Imperative===
<langsyntaxhighlight AppleScriptlang="applescript">set n to 5
set k to 3
 
Line 253 ⟶ 258:
 
return n_factorial / (n_minus_k_factorial) * 1 / (k_factorial) as integer
</syntaxhighlight>
</lang>
 
===Functional===
Line 259 ⟶ 264:
Using a little more abstraction for readability, and currying for ease of both re-use and refactoring:
 
<langsyntaxhighlight lang="applescript">-- factorial :: Int -> Int
on factorial(n)
product(enumFromTo(1, n))
Line 336 ⟶ 341:
foldl(multiply, 1, xs)
end product</langsyntaxhighlight>
{{Out}}
<pre>{10, 10}</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">factorial: function [n]-> product 1..n
binomial: function [x,y]-> (factorial x) / (factorial y) * factorial x-y
 
print binomial 5 3</syntaxhighlight>
 
{{out}}
 
<pre>10</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">MsgBox, % Round(BinomialCoefficient(5, 3))
 
;---------------------------------------------------------------------------
Line 352 ⟶ 368:
}
Return, r
}</langsyntaxhighlight>
Message box shows:
<pre>10</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f EVALUATE_BINOMIAL_COEFFICIENTS.AWK
BEGIN {
Line 372 ⟶ 388:
printf("%d %d = %d\n",n,k,r)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 381 ⟶ 397:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off & setlocal
 
if "%~2"=="" ( echo Usage: %~nx0 n k && goto :EOF )
Line 397 ⟶ 413:
for /L %%I in (1, 1, %~3) do set /a coeff /= %%I
endlocal && set "%~1=%coeff%"
goto :EOF</langsyntaxhighlight>
 
{{Out}}
Line 420 ⟶ 436:
</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.
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">
GET "libhdr"
 
LET choose(n, k) =
~(0 <= k <= n) -> 0,
2*k > n -> binomial(n, n - k),
binomial(n, k)
 
AND binomial(n, k) =
k = 0 -> 1,
binomial(n, k - 1) * (n - k + 1) / k
 
LET start() = VALOF {
LET n, k = ?, ?
LET argv = VEC 20
LET sz = ?
 
sz := rdargs("n/a/n/p,k/a/n/p", argv, 20)
UNLESS sz ~= 0 RESULTIS 1
 
n := !argv!0
k := !argv!1
 
writef("%d choose %d = %d *n", n, k, choose(n, k))
RESULTIS 0
}
</syntaxhighlight>
{{Out}}
Note that with the /p flag to rdargs(), the system will prompt if we don't supply both arguments on the command line.
<pre>
$ cintsys64
 
BCPL 64-bit Cintcode System (13 Jan 2020)
0.004> nCk 50 25
50 choose 25 = 126410606437752
0.003> nCk 10 5
10 choose 5 = 252
0.004> nCk 100 2
100 choose 2 = 4950
0.000> nCk 100 98
100 choose 98 = 4950
0.004> nCk
n > 5
k > 3
5 choose 3 = 10
</pre>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> @%=&1010
PRINT "Binomial (5,3) = "; FNbinomial(5, 3)
Line 442 ⟶ 506:
ENDWHILE
= R%
</syntaxhighlight>
</lang>
{{Out}}
<pre>Binomial (5,3) = 10
Line 449 ⟶ 513:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">(binomial=
n k coef
. !arg:(?n,?k)
Line 465 ⟶ 529:
binomial$(5,3)
10
</syntaxhighlight>
</lang>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) 5 3nr
10
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <limits.h>
 
Line 517 ⟶ 581:
printf("%lu\n", binomial(67, 31));
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>10
Line 524 ⟶ 588:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
namespace BinomialCoefficients
Line 560 ⟶ 624:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">double Factorial(double nValue)
{
double result = nValue;
Line 584 ⟶ 648:
return Factorial(n) /(Factorial(k)*Factorial((n - k)));
}
</syntaxhighlight>
</lang>
 
Implementation:
<langsyntaxhighlight lang="cpp">int main()
{
cout<<"The Binomial Coefficient of 5, and 3, is equal to: "<< binomialCoefficient(5,3);
cin.get();
}</langsyntaxhighlight>
 
{{Out}}
Line 597 ⟶ 661:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn binomial-coefficient [n k]
(let [rprod (fn [a b] (reduce * (range a (inc b))))]
(/ (rprod (- n k -1) n) (rprod 1 k))))</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
binomial_coefficient = (n, k) ->
result = 1
Line 612 ⟶ 676:
for k in [0..n]
console.log "binomial_coefficient(#{n}, #{k}) = #{binomial_coefficient(n,k)}"
</syntaxhighlight>
</lang>
 
{{Out}}<pre>
Line 623 ⟶ 687:
binomial_coefficient(5, 5) = 1
</pre>
 
 
 
 
=={{header|Commodore BASIC}}==
<syntaxhighlight lang="freebasic">
10 REM BINOMIAL COEFFICIENTS
20 REM COMMODORE BASIC 2.0
30 REM 2021-08-24
40 REM BY ALVALONGO
100 Z=0:U=1
110 FOR N=U TO 10
120 PRINT N;
130 FOR K=Z TO N
140 GOSUB 900
150 PRINT C;
160 NEXT K
170 PRINT
180 NEXT N
190 END
900 REM BINOMIAL COEFFICIENT
910 IF K<Z OR K>N THEN C=Z:RETURN
920 IF K=Z OR K=N THEN C=U:RETURN
930 P=K:IF N-K<P THEN P=N-K
940 C=U
950 FOR I=Z TO P-U
960 C=C/(I+U)*(N-I)
980 NEXT I
990 RETURN
</syntaxhighlight>
 
 
 
 
 
 
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defun choose (n k)
(labels ((prod-enum (s e)
Line 631 ⟶ 731:
(fact (n) (prod-enum 1 n)))
(/ (prod-enum (- (1+ n) k) n) (fact k))))
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">T binomial(T)(in T n, T k) pure nothrow {
if (k > (n / 2))
k = n - k;
Line 649 ⟶ 749:
writefln("(%3d %3d) = %s", d[0], d[1], binomial(d[0], d[1]));
writeln("(100 50) = ", binomial(100.BigInt, 50.BigInt));
}</langsyntaxhighlight>
{{out}}
<pre>( 5 3) = 2
Line 656 ⟶ 756:
(100 50) = 1976664223067613962806675336</pre>
 
The above wouldn't work for me (100C50 correctly gives 100891344545564193334812497256). This next one is a translation of C#:
 
<lang d>T BinomialCoeff(T)(in T n, in T k)
{{trans|C#}}
 
<syntaxhighlight lang="d">T BinomialCoeff(T)(in T n, in T k)
{
T nn = n, kk = k, c = cast(T)1;
Line 678 ⟶ 781:
BinomialCoeff(10UL, 3UL).writeln;
BinomialCoeff(100.BigInt, 50.BigInt).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>120
Line 684 ⟶ 787:
 
=={{header|dc}}==
<langsyntaxhighlight lang="dc">[sx1q]sz[d0=zd1-lfx*]sf[skdlfxrlk-lfxlklfx*/]sb</langsyntaxhighlight>
 
Demonstration:
 
<syntaxhighlight lang ="dc">5 3lbxp</langsyntaxhighlight>
<tt>10</tt>
 
Annotated version:
 
<langsyntaxhighlight lang="dc">[ macro z: factorial base case when n is (z)ero ]sx
[sx [ x is our dump register; get rid of extraneous copy of n we no longer need]sx
1 [ return value is 1 ]sx
Line 723 ⟶ 826:
] sb
 
5 3 lb x p [print(5 choose 3)]sx</langsyntaxhighlight>
 
=={{header|Delphi}}==
 
<langsyntaxhighlight Delphilang="delphi">program Binomial;
 
{$APPTYPE CONSOLE}
Line 754 ⟶ 857:
Writeln('C(5,3) is ', BinomialCoff(5, 3));
ReadLn;
end.</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func binomial n k .
if k > n / 2
k = n - k
.
numer = 1
for i = n downto n - k + 1
numer = numer * i
.
denom = 1
for i = 1 to k
denom = denom * i
.
return numer / denom
.
print binomial 5 3
</syntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def choose(n,k) when is_integer(n) and is_integer(k) and n>=0 and k>=0 and n>=k do
if k==0, do: 1, else: choose(n,k,1,1)
Line 768 ⟶ 890:
 
IO.inspect RC.choose(5,3)
IO.inspect RC.choose(60,30)</langsyntaxhighlight>
 
{{out}}
Line 777 ⟶ 899:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
choose(N, 0) -> 1;
choose(N, K) when is_integer(N), is_integer(K), (N >= 0), (K >= 0), (N >= K) ->
Line 786 ⟶ 908:
choose(N, K, I, Acc) ->
choose(N, K, I+1, (Acc * (N-I+1)) div I).
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
<syntaxhighlight lang="text">PROGRAM BINOMIAL
 
!$DOUBLE
Line 816 ⟶ 938:
PRINT("Binomial (33,17) = ";BIN)
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>Binomial (5,3) = 10
Line 824 ⟶ 946:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
let choose n k = List.fold (fun s i -> s * (n-i+1)/i ) 1 [1..k]
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">
: fact ( n -- n-factorial )
dup 0 = [ drop 1 ] [ dup 1 - fact * ] if ;
Line 845 ⟶ 967:
: choose-fold ( n k -- n-choose-k )
2dup 1 + [a,b] product -rot - 1 [a,b] product / ;
</syntaxhighlight>
</lang>
 
=={{header|Fermat}}==
The binomial function is built in.
<syntaxhighlight lang="fermat">Bin(5,3)</syntaxhighlight>
{{out}}<pre>10</pre>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: choose ( n k -- nCk ) 1 swap 0 ?do over i - i 1+ */ loop nip ;
 
5 3 choose . \ 10
33 17 choose . \ 1166803110</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 857 ⟶ 984:
=== Direct Method ===
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program test_choose
 
implicit none
Line 887 ⟶ 1,014:
end function choose
 
end program test_choose</langsyntaxhighlight>
{{Out}}<pre>10</pre>
 
=== Avoiding Overflow ===
Of course this method doesn't avoid overflow completely just delays it. It could be extended by adding more entries to the '''primes''' array
<langsyntaxhighlight lang="fortran">
program binomial
integer :: i, j
Line 936 ⟶ 1,063:
 
end program binomial
</syntaxhighlight>
</lang>
 
{{Out}}
Line 967 ⟶ 1,094:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function factorial(n As Integer) As Integer
Line 997 ⟶ 1,124:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,021 ⟶ 1,148:
Frink has a built-in efficient function to find binomial coefficients.
It produces arbitrarily-large integers.
<langsyntaxhighlight lang="frink">
println[binomial[5,3]]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
FunL has pre-defined function <code>choose</code> in module <code>integers</code>, which is defined as:
<langsyntaxhighlight lang="funl">def
choose( n, k ) | k < 0 or k > n = 0
choose( n, 0 ) = 1
Line 1,034 ⟶ 1,161:
 
println( choose(5, 3) )
println( choose(60, 30) )</langsyntaxhighlight>
{{out}}
<pre>
Line 1,042 ⟶ 1,169:
 
Here it is defined using the recommended formula for this task.
<langsyntaxhighlight lang="funl">import integers.factorial
 
def
binomial( n, k ) | k < 0 or k > n = 0
binomial( n, k ) = factorial( n )/factorial( n - k )/factorial( k )</langsyntaxhighlight>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Built-in
Binomial(5, 3);
# 10</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
import "fmt"
import "math/big"
Line 1,061 ⟶ 1,188:
fmt.Println(new(big.Int).Binomial(5, 3))
fmt.Println(new(big.Int).Binomial(60, 30))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,070 ⟶ 1,197:
=={{header|Golfscript}}==
Actually evaluating n!/(k! (n-k)!):
<langsyntaxhighlight lang="golfscript">;5 3 # Set up demo input
{),(;{*}*}:f; # Define a factorial function
.f@.f@/\@-f/</langsyntaxhighlight>
But Golfscript is meant for golfing, and it's shorter to calculate <math>\prod_{i=0}^{k-1} \frac{n-i}{i+1}</math>:
 
<langsyntaxhighlight lang="golfscript">;5 3 # Set up demo input
1\,@{1$-@\*\)/}+/</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def factorial = { x ->
assert x > -1
x == 0 ? 1 : (1..x).inject(1G) { BigInteger product, BigInteger factor -> product *= factor }
Line 1,089 ⟶ 1,216:
assert n >= k
factorial(n).intdiv(factorial(k)*factorial(n-k))
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">assert combinations(20, 0) == combinations(20, 20)
assert combinations(20, 10) == (combinations(19, 9) + combinations(19, 10))
assert combinations(5, 3) == 10
println combinations(5, 3)</langsyntaxhighlight>
 
{{Out}}
<pre>10</pre>
 
=={{header|GW-BASIC}}==
<syntaxhighlight lang="gwbasic">10 REM BINOMIAL CALCULATOR
20 INPUT "N? ", N
30 INPUT "P? ", P
40 GOSUB 70
50 PRINT C
60 END
70 C = 0
80 IF N < 0 OR P<0 OR P > N THEN RETURN
90 IF P < N\2 THEN P = N - P
100 C = 1
110 FOR I = N TO P+1 STEP -1
120 C=C*I
130 NEXT I
140 FOR I = 1 TO N-P
150 C=C/I
160 NEXT I
170 RETURN</syntaxhighlight>
 
=={{header|Haskell}}==
The only trick here is realizing that everything's going to divide nicely, so we can use div instead of (/).
 
<langsyntaxhighlight lang="haskell">
choose :: (Integral a) => a -> a -> a
choose n k = product [k+1..n] `div` product [1..n-k]
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="haskell">> 5 `choose` 3
10</langsyntaxhighlight>
 
Or, generate the binomial coefficients iteratively to avoid computing with big numbers:
 
<langsyntaxhighlight lang="haskell">
choose :: (Integral a) => a -> a -> a
choose n k = foldl (\z i -> (z * (n-i+1)) `div` i) 1 [1..k]
</syntaxhighlight>
</lang>
 
Or using "caching":
 
<langsyntaxhighlight lang="haskell">coeffs = iterate next [1]
where
next ns = zipWith (+) (0:ns) $ ns ++ [0]
 
main = print $ coeffs !! 5 !! 3</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">WRITE(Messagebox) BinomCoeff( 5, 3) ! displays 10
 
FUNCTION factorial( n )
Line 1,138 ⟶ 1,284:
FUNCTION BinomCoeff( n, k )
BinomCoeff = factorial(n)/factorial(n-k)/factorial(k)
END</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">link math, factors
 
procedure main()
write("choose(5,3)=",binocoef(5,3))
end</langsyntaxhighlight>
{{Out}}
<pre>choose(5,3)=10</pre>
Line 1,153 ⟶ 1,299:
[http://www.cs.arizona.edu/icon/library/src/procs/factors.icn factors provides factorial].
 
<langsyntaxhighlight Iconlang="icon">procedure binocoef(n, k) #: binomial coefficient
 
k := integer(k) | fail
Line 1,179 ⟶ 1,325:
return i
 
end</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Binomial.bas"
110 PRINT "Binomial (5,3) =";BINOMIAL(5,3)
120 DEF BINOMIAL(N,K)
Line 1,194 ⟶ 1,340:
200 LOOP
210 LET BINOMIAL=R
220 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,201 ⟶ 1,347:
 
'''Example usage:'''
<langsyntaxhighlight lang="j"> 3 ! 5
10</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class Binomial {
 
// precise, but may overflow and then produce completely incorrect results
Line 1,275 ⟶ 1,421:
demo(1000, 300);
}
}</langsyntaxhighlight>
{{Out}}
<pre>5 3 10 10 10.0 10
Line 1,282 ⟶ 1,428:
Recursive version, without overflow check:
 
<langsyntaxhighlight lang="java">public class Binomial
{
private static long binom(int n, int k)
Line 1,298 ⟶ 1,444:
System.out.println(binom(5, 3));
}
}</langsyntaxhighlight>
{{Out}}
<pre>10</pre>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">function binom(n, k) {
var coeff = 1;
var i;
Line 1,316 ⟶ 1,462:
}
 
console.log(binom(5, 3));</langsyntaxhighlight>
{{Out}}
<pre>10</pre>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq"># nCk assuming n >= k
def binomial(n; k):
if k > n / 2 then binomial(n; n-k)
Line 1,333 ⟶ 1,479:
 
([5,3], [100,2], [ 33,17]) | task
</syntaxhighlight>
</lang>
{{out}}
5 C 3 = 10
Line 1,343 ⟶ 1,489:
 
'''Built-in'''
<syntaxhighlight lang ="julia">@show binomial(5, 3)</langsyntaxhighlight>
 
'''Recursive version''':
<langsyntaxhighlight lang="julia">function binom(n::Integer, k::Integer)
n ≥ k || return 0 # short circuit base cases
(n == 1 || k == 0) && return 1
Line 1,353 ⟶ 1,499:
end
 
@show binom(5, 3)</langsyntaxhighlight>
 
{{out}}
Line 1,360 ⟶ 1,506:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> {[n;k]_(*/(k-1)_1+!n)%(*/1+!k)} . 5 3
10</langsyntaxhighlight>
 
Alternative version:
<langsyntaxhighlight Klang="k"> {[n;k]i:!(k-1);_*/((n-i)%(i+1))} . 5 3
10</langsyntaxhighlight>
 
Using Pascal's triangle:
<langsyntaxhighlight Klang="k"> pascal:{x{+':0,x,0}\1}
pascal 5
(1
Line 1,378 ⟶ 1,524:
 
{[n;k](pascal n)[n;k]} . 5 3
10</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 2.0
 
fun binomial(n: Int, k: Int) = when {
Line 1,403 ⟶ 1,549:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,425 ⟶ 1,571:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
 
{def C
Line 1,457 ⟶ 1,603:
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
 
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define binomial(n::integer,k::integer) => {
#k == 0 ? return 1
local(result = 1)
Line 1,471 ⟶ 1,617:
binomial(5, 3)
binomial(5, 4)
binomial(60, 30)</langsyntaxhighlight>
 
{{Out}}
Line 1,479 ⟶ 1,625:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
' [RC] Binomial Coefficients
 
Line 1,502 ⟶ 1,648:
end function
</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to choose :n :k
if :k = 0 [output 1]
output (choose :n :k-1) * (:n - :k + 1) / :k
Line 1,511 ⟶ 1,657:
 
show choose 5 3 ; 10
show choose 60 30 ; 1.18264581564861e+17</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function Binomial( n, k )
if k > n then return nil end
if k > n/2 then k = n - k end -- (n k) = (n n-k)
Line 1,524 ⟶ 1,670:
end
return numer / denom
end</langsyntaxhighlight>
 
Additive recursion with memoization by hashing 2 input integer.
Lua 5.3 support bit-wise operation; assume 64 bit integer implementation here.
<langsyntaxhighlight lang="lua">local Binomial = setmetatable({},{
__call = function(self,n,k)
local hash = (n<<32) | (k & 0xffffffff)
Line 1,558 ⟶ 1,704:
})
print( Binomial(100,50)) -- 1.0089134454556e+029
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">convert(binomial(n,k),factorial);
 
binomial(5,3);</langsyntaxhighlight>
{{Out}}
<pre> factorial(n)
Line 1,572 ⟶ 1,718:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">(Local) In[1]:= Binomial[5,3]
(Local) Out[1]= 10</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 1,579 ⟶ 1,725:
 
Solution:
<langsyntaxhighlight MATLABlang="matlab">>> nchoosek(5,3)
ans =
10</langsyntaxhighlight>
 
Alternative implementations are:
 
<langsyntaxhighlight MATLABlang="matlab">function r = binomcoeff1(n,k)
r = diag(rot90(pascal(n+1))); % vector of all binomial coefficients for order n
r = r(k);
end; </langsyntaxhighlight>
 
<langsyntaxhighlight MATLABlang="matlab">function r = binomcoeff2(n,k)
prod((n-k+1:n)./(1:k))
end; </langsyntaxhighlight>
 
<langsyntaxhighlight MATLABlang="matlab">function r = binomcoeff3(n,k)
m = pascal(max(n-k,k)+1);
r = m(n-k+1,k+1);
end; </langsyntaxhighlight>
 
If you want a vectorized function that returns multiple binomial coefficients given vector inputs, you must define that function yourself. A sample implementation is given below. This function takes either scalar or vector inputs for "n" and "v" and returns either a: scalar, vector, or matrix. Where the columns are indexed by the "k" vector and the rows indexed by the "n" vector.
binomialCoeff.m:
<langsyntaxhighlight MATLABlang="matlab">function coefficients = binomialCoeff(n,k)
 
coefficients = zeros(numel(n),numel(k)); %Preallocate memory
Line 1,621 ⟶ 1,767:
end
end %binomialCoeff</langsyntaxhighlight>
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> binomialCoeff((0:5),(0:5))
 
ans =
Line 1,662 ⟶ 1,808:
ans =
 
10</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">binomial( 5, 3); /* 10 */
binomial(-5, 3); /* -35 */
binomial( 5, -3); /* 0 */
Line 1,677 ⟶ 1,823:
 
binomial(a, b); /* binomial(a, b) */
makegamma(%); /* gamma(a + 1)/(gamma(-b + a + 1)*gamma(b + 1)) */</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang="min">((dup 0 ==) 'succ (dup pred) '* linrec) :fact
('dup dip dup ((fact) () (- fact) (fact * div)) spread) :binomial
 
5 3 binomial puts!</langsyntaxhighlight>
{{out}}
<pre>
Line 1,691 ⟶ 1,837:
 
=={{header|MINIL}}==
<langsyntaxhighlight lang="minil">// Number of combinations nCr
00 0E Go: ENT R0 // n
01 1E ENT R1 // r
Line 1,723 ⟶ 1,869:
1D C9 JNZ Next
1E 03 R0 = R3
1F 80 JZ Go // Display result</langsyntaxhighlight>
 
This uses the recursive definition:
Line 1,734 ⟶ 1,880:
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П1 <-> П0 ПП 22 П2 ИП1 ПП 22 П3
ИП0 ИП1 - ПП 22 ИП3 * П3 ИП2 ИП3
/ С/П ВП П0 1 ИП0 * L0 25 В/О</langsyntaxhighlight>
 
''Input'': ''n'' ^ ''k'' В/О С/П.
Line 1,742 ⟶ 1,888:
=={{header|Nanoquery}}==
{{trans|Python}}
<langsyntaxhighlight Nanoquerylang="nanoquery">def binomialCoeff(n, k)
result = 1
for i in range(1, k)
Line 1,752 ⟶ 1,898:
if main
println binomialCoeff(5,3)
end</langsyntaxhighlight>
 
=={{header|Nim}}==
Note that a function to compute these coefficients, named “binom”, is available in standard module “math”.
<langsyntaxhighlight lang="nim">proc binomialCoeff(n, k: int): int =
result = 1
for i in 1..k:
result = result * (n-i+1) div i
 
echo binomialCoeff(5, 3)</langsyntaxhighlight>
{{Out}}
<pre>10</pre>
 
=={{header|Oberon-2}}==
{{works with|oo2c}}
<langsyntaxhighlight lang="oberon2">
MODULE Binomial;
IMPORT
Line 1,789 ⟶ 1,935:
Out.Int(For(5,2),0);Out.Ln
END Binomial.
</syntaxhighlight>
</lang>
{{Out}}
<pre>10</pre>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">
<lang OCaml>
let binomialCoeff n p =
let p = if p < n -. p then p else n -. p in
Line 1,805 ⟶ 1,951:
else res in
cm 1. n 1.
</syntaxhighlight>
</lang>
=== Alternate version using big integers ===
<langsyntaxhighlight lang="ocaml">#load "nums.cma";;
open Num;;
 
Line 1,817 ⟶ 1,963:
else a (succ j) ((v */ (Int (n - j))) // (Int (succ j)))
in a 0 (Int 1)
;;</langsyntaxhighlight>
 
=== Simple recursive version ===
<langsyntaxhighlight OCamllang="ocaml">open Num;;
let rec binomial n k = if n = k then Int 1 else ((binomial (n-1) k) */ Int n) // Int (n-k)</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: binomial(n, k) | i | 1 k loop: i [ n i - 1+ * i / ] ;</langsyntaxhighlight>
 
{{out}}
Line 1,835 ⟶ 1,981:
=={{header|Oz}}==
{{trans|Python}}
<langsyntaxhighlight lang="oz">declare
fun {BinomialCoeff N K}
{List.foldL {List.number 1 K 1}
Line 1,844 ⟶ 1,990:
end
in
{Show {BinomialCoeff 5 3}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang ="parigp">binomial(5,3)</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,853 ⟶ 1,999:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub binomial {
use bigint;
my ($r, $n, $k) = (1, @_);
Line 1,860 ⟶ 2,006:
}
print binomial(5, 3);</langsyntaxhighlight>
 
{{out}}
Line 1,866 ⟶ 2,012:
 
Since the bigint module already has a binomial method, this could also be written as:
<langsyntaxhighlight lang="perl">sub binomial {
use bigint;
my($n,$k) = @_;
(0+$n)->bnok($k);
}</langsyntaxhighlight>
 
For better performance, especially with large inputs, one can also use something like:
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/binomial/;
print length(binomial(100000,50000)), "\n";</langsyntaxhighlight>
{{out}}
<pre>30101</pre>
Line 1,882 ⟶ 2,028:
 
=={{header|Phix}}==
There is a builtin choose() function which does this. From builtins/factorial.e (an autoinclude):
<!--<syntaxhighlight lang="phix">-->
<lang Phix>global function choose(integer n, k)
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #000000;">choose</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">)</span>
atom res = 1
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
for i=1 to k do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">k</span> <span style="color: #008080;">do</span>
res = (res*(n-i+1))/i
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">))/</span><span style="color: #000000;">i</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return res
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
end function</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</syntaxhighlight>-->
Example:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>?choose(5,3)</lang>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">choose</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,898 ⟶ 2,048:
However errors will creep in should any result or interim value exceed 9,007,199,254,740,992 (on 32-bit), so:
{{libheader|Phix/mpfr}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>include builtins\mpfr.e
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
?mpz_get_str(mpz_binom(5,3))
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
?mpz_get_str(mpz_binom(100,50))
<span style="color: #004080;">sequence</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,</span><span style="color: #000000;">50</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">60</span><span style="color: #0000FF;">,</span><span style="color: #000000;">30</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">1200</span><span style="color: #0000FF;">,</span><span style="color: #000000;">120</span><span style="color: #0000FF;">}}</span>
?mpz_get_str(mpz_binom(60,30))
<span style="color: #004080;">mpz</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">()</span>
?mpz_get_str(mpz_binom(1200,120))</lang>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #7060A8;">mpz_bin_uiui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,910 ⟶ 2,066:
"1004576581793084916475353119318331966507299414258370667602185866686463289093457468590558508056798211449853806741873396451735444387513582540860551330127062642417424083600"
</pre>
Note that I have re-implemented mpz_bin_uiui() mainly for the benefit of pwa/p2js, and some tweaks may be in order (please ask if needed) to match gmp proper for -ve n.
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
$n=5;
$k=3;
Line 1,921 ⟶ 2,078:
$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));
echo $binomial_coefficient;
?></langsyntaxhighlight>
 
Alternative version, not based on factorial
<syntaxhighlight lang="php">
<lang PHP>
function binomial_coefficient($n, $k) {
if ($k == 0) return 1;
Line 1,933 ⟶ 2,090:
return $result;
}
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
 
===Iterative===
<syntaxhighlight lang="picat">binomial_it(N,K) = Res =>
if K < 0 ; K > N then
R = 0
else
R = 1,
foreach(I in 0..K-1)
R := R * (N-I) // (I+1)
end
end,
Res = R.</syntaxhighlight>
 
===Using built-in factorial/1===
<syntaxhighlight lang="picat">binomial_fac(N,K) = factorial(N) // factorial(K) // factorial(N-K).</syntaxhighlight>
 
===Recursion (tabled)===
<syntaxhighlight lang="picat">table
binomial_rec(_N, 0) = 1.
binomial_rec(0, _K) = 0.
binomial_rec(N, K) = binomial_rec(N-1,K-1) + binomial_rec(N-1,K).</syntaxhighlight>
 
===Test===
<syntaxhighlight lang="picat">go =>
Tests = [[10,3],[60,30],[100,50],[400,200]],
foreach([N,K] in Tests)
println([N,K,binomial_it(N,K)])
end,
nl.
</syntaxhighlight>
 
 
All methods prints the same result.
 
{{out}}
<pre>
[10,3,120]
[60,30,118264581564861424]
[100,50,100891344545564193334812497256]
[400,200,102952500135414432972975880320401986757210925381077648234849059575923332372651958598336595518976492951564048597506774120]</pre>
 
binomial_rec/2 is a little slower than the two other (0.036s vs 0.002s on these tests).
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de binomial (N K)
(let f
'((N)
Line 1,942 ⟶ 2,143:
(/
(f N)
(* (f (- N K)) (f K)) ) ) )</langsyntaxhighlight>
{{Out}}
<pre>: (binomial 5 3)
Line 1,948 ⟶ 2,149:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
binomial_coefficients:
procedure options (main);
Line 1,971 ⟶ 2,172:
end fact;
end binomial_coefficients;
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,978 ⟶ 2,179:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function choose($n,$k) {
if($k -le $n -and 0 -le $k) {
Line 1,996 ⟶ 2,197:
choose 10 2
choose 10 8
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,007 ⟶ 2,208:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Factor(n)
Protected Result=1
While n>0
Line 2,027 ⟶ 2,228:
Print("Press ENTER to quit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
'''Example
Enter value n: 5
Line 2,035 ⟶ 2,236:
=={{header|Python}}==
===Imperative===
<langsyntaxhighlight lang="python">def binomialCoeff(n, k):
result = 1
for i in range(1, k+1):
Line 2,042 ⟶ 2,243:
 
if __name__ == "__main__":
print(binomialCoeff(5, 3))</langsyntaxhighlight>
{{Out}}
<pre>10</pre>
 
===Functional===
<langsyntaxhighlight lang="python">from operator import mul
from functools import reduce
 
Line 2,069 ⟶ 2,270:
else:
return ( reduce( mul, range((n - r + 1), n + 1), 1)
// reduce( mul, range(1, r + 1), 1) )</langsyntaxhighlight>
 
 
Line 2,075 ⟶ 2,276:
 
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Evaluation of binomial coefficients'''
 
from functools import reduce
Line 2,134 ⟶ 2,335:
# TESTS ---------------------------------------------------
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>10
Line 2,141 ⟶ 2,342:
Compare the use of Python comments, (above); with the use of Python type hints, (below).
 
<langsyntaxhighlight lang="python">from typing import (Callable, List, Any)
from functools import reduce
from operator import mul
Line 2,165 ⟶ 2,366:
print(binomialCoefficient(5)(3))
# k=0 to k=5, where n=5
print(list(map(binomialCoefficient(5), enumFromTo(0)(5))))</langsyntaxhighlight>
{{Out}}
<pre>10
[1, 5, 10, 10, 5, 1]</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ tuck - over
1 swap times
[ over i + 1+ * ]
nip swap times
[ i 1+ / ] ] is binomial ( n n --> )
 
5 3 binomial echo</syntaxhighlight>
 
{{out}}
 
<pre>10</pre>
 
 
=={{header|R}}==
R's built-in choose() function evaluates binomial coefficients:
<syntaxhighlight lang ="r">choose(5,3)</langsyntaxhighlight>
 
{{Out}}
Line 2,178 ⟶ 2,394:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
(binomial 10 5)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
For a start, you can get the length of the corresponding list of combinations:
<syntaxhighlight lang="raku" perl6line>say combinations(5, 3).elems;</langsyntaxhighlight>
{{out}}
<pre>10</pre>
Line 2,193 ⟶ 2,409:
This method is efficient, as Raku will not actually compute each element of the list, since it actually uses an iterator with a defined <tt>count-only</tt> method. Such method performs computations in a way similar to the following infix operator:
 
<syntaxhighlight lang="raku" perl6line>sub infix:<choose> { [*] ($^n ... 0) Z/ 1 .. $^p }
say 5 choose 3;</langsyntaxhighlight>
 
A possible optimization would use a symmetry property of the binomial coefficient:
 
<syntaxhighlight lang="raku" perl6line>sub infix:<choose> { [*] ($^n ... 0) Z/ 1 .. min($n - $^p, $p) }</langsyntaxhighlight>
 
One drawback of this method is that it returns a Rat, not an Int. So we actually may want to enforce the conversion:
<syntaxhighlight lang="raku" perl6line>sub infix:<choose> { ([*] ($^n ... 0) Z/ 1 .. min($n - $^p, $p)).Int }</langsyntaxhighlight>
 
And ''this'' is exactly what the <tt>count-only</tt> method does.
Line 2,208 ⟶ 2,424:
The task is to compute ANY binomial coefficient(s), but these REXX examples are limited to 100k digits.
===idiomatic===
<langsyntaxhighlight lang="rexx">/*REXX program calculates binomial coefficients (also known as combinations). */
numeric digits 100000 /*be able to handle gihugeic numbers. */
parse arg n k . /*obtain N and K from the C.L. */
Line 2,215 ⟶ 2,431:
/*──────────────────────────────────────────────────────────────────────────────────────*/
comb: procedure; parse arg x,y; return !(x) % (!(x-y) * !(y))
!: procedure; !=1; do j=2 to arg(1); !=!*j; end /*j*/; return !</langsyntaxhighlight>
'''output''' when using the input of: &nbsp; <tt> 5 &nbsp; 3 </tt>
<pre>
Line 2,228 ⟶ 2,444:
This REXX version takes advantage of reducing the size (product) of the numerator, and also,
<br>only two (factorial) products need be calculated.
<langsyntaxhighlight lang="rexx">/*REXX program calculates binomial coefficients (also known as combinations). */
numeric digits 100000 /*be able to handle gihugeic numbers. */
parse arg n k . /*obtain N and K from the C.L. */
Line 2,236 ⟶ 2,452:
comb: procedure; parse arg x,y; return pfact(x-y+1, x) % pfact(2, y)
/*──────────────────────────────────────────────────────────────────────────────────────*/
pfact: procedure; !=1; do j=arg(1) to arg(2); !=!*j; end /*j*/; return !</langsyntaxhighlight>
'''output''' &nbsp; is identical to the 1<sup>st</sup> REXX version.
 
Line 2,243 ⟶ 2,459:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
numer = 0
binomial(5,3)
Line 2,256 ⟶ 2,472:
next
return numer
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
RPL has a <code>COMB</code> instruction which returns the result directly. If a home-made function is preferred, there are many possibilities.
 
Using the recommended formula and the stack:
≪ - LAST ! SWAP ! SWAP ROT ! * / ≫ ‘'''CHOOS'''’ STO
Using the formula with local variables:
≪ → n k ≪ n ! n k - ! / k ! / ≫ ≫ ‘'''CHOOS'''’ STO
To avoid data overflow for high values of n, using the formula simplified by (n-k)! :
≪ → n k ≪ 1 n k - 1 + n '''FOR''' j j * '''NEXT''' k ! / ≫ ≫ ‘'''CHOOS'''’ STO
All the above functions are called the same way and return the same result:
5 3 '''CHOOS'''
{{out}}
<pre>
10
</pre>
 
=={{header|Ruby}}==
Line 2,262 ⟶ 2,494:
 
{{works with|Ruby|1.8.7+}}
<langsyntaxhighlight lang="ruby">class Integer
# binomial coefficient: n C k
def choose(k)
Line 2,274 ⟶ 2,506:
 
p 5.choose(3)
p 60.choose(30)</langsyntaxhighlight>
result
<pre>10
Line 2,281 ⟶ 2,513:
another implementation:
 
<langsyntaxhighlight lang="ruby">
def c n, r
(0...r).inject(1) do |m,i| (m * (n - i)) / (i + 1) end
end
</langsyntaxhighlight>Ruby's Arrays have a combination method which result in a (lazy) enumerator. This Enumerator has a "size" method, which returns the size of the enumerator, or nil if it can’t be calculated lazily. (Since Ruby 2.0)
<langsyntaxhighlight lang="ruby">(1..60).to_a.combination(30).size #=> 118264581564861424</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">print "binomial (5,1) = "; binomial(5, 1)
print "binomial (5,2) = "; binomial(5, 2)
print "binomial (5,3) = "; binomial(5, 3)
Line 2,305 ⟶ 2,537:
next i
binomial = coeff
end function</langsyntaxhighlight>
{{Out}}
<pre>binomial (5,1) = 5
Line 2,314 ⟶ 2,546:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn fact(n:u32) -> u64 {
let mut f:u64 = n as u64;
for i in 2..n {
Line 2,332 ⟶ 2,564:
fn main() {
println!("{}", choose(5,3));
}</langsyntaxhighlight>
{{Out}}
<pre>10</pre>
Line 2,338 ⟶ 2,570:
Alternative version, using functional style:
 
<langsyntaxhighlight lang="rust">fn choose(n:u64,k:u64)->u64 {
let factorial=|x| (1..=x).fold(1, |a, x| a * x);
factorial(n) / factorial(k) / factorial(n - k)
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object Binomial {
def main(args: Array[String]): Unit = {
val n=5
Line 2,354 ⟶ 2,586:
def binomialCoefficient(n:Int, k:Int)=fact(n) / (fact(k) * fact(n-k))
def fact(n:Int):Int=if (n==0) 1 else n*fact(n-1)
}</langsyntaxhighlight>
{{Out}}
<pre>The Binomial Coefficient of 5 and 3 equals 10.</pre>
Line 2,360 ⟶ 2,592:
Another (more flexible and efficient) implementation. n and k are taken from command line. The use of BigInts allows to compute coefficients of arbitrary size:
 
<langsyntaxhighlight lang="scala">object Binomial extends App {
def binomialCoefficient(n: Int, k: Int) =
(BigInt(n - k + 1) to n).product /
Line 2,367 ⟶ 2,599:
val Array(n, k) = args.map(_.toInt)
println("The Binomial Coefficient of %d and %d equals %,3d.".format(n, k, binomialCoefficient(n, k)))
}</langsyntaxhighlight>
 
{{Out}}
Line 2,374 ⟶ 2,606:
 
Using recursive formula <code>C(n,k) = C(n-1,k-1) + C(n-1,k)</code>:
<langsyntaxhighlight lang="scala"> def bico(n: Long, k: Long): Long = (n, k) match {
case (n, 0) => 1
case (0, k) => 0
case (n, k) => bico(n - 1, k - 1) + bico(n - 1, k)
}
println("bico(5,3) = " + bico(5, 3))</langsyntaxhighlight>
{{Out}}
<pre>bico(5,3) = 10</pre>
Line 2,385 ⟶ 2,617:
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<langsyntaxhighlight lang="scheme">(define (factorial n)
(define (*factorial n acc)
(if (zero? n)
Line 2,396 ⟶ 2,628:
 
(display (choose 5 3))
(newline)</langsyntaxhighlight>
{{Out}}
<pre>10</pre>
Line 2,402 ⟶ 2,634:
Alternatively a recursive implementation can be constructed from Pascal's Triangle:
 
<langsyntaxhighlight lang="scheme">(define (pascal i j)
(cond ((= i 0) 1)
((= j 0) 1)
Line 2,413 ⟶ 2,645:
 
(display (choose 5 3))
(newline)</langsyntaxhighlight>
{{Out}}
<pre>10</pre>
Line 2,422 ⟶ 2,654:
E.g.: <tt>(-6) ! 10</tt> evaluates to 3003.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,435 ⟶ 2,667:
writeln;
end for;
end func;</langsyntaxhighlight>
 
{{Out}}
Line 2,467 ⟶ 2,699:
for the type [http://seed7.sourceforge.net/manual/types.htm#bigInteger bigInteger]:
 
<langsyntaxhighlight lang="seed7">const func bigInteger: (in bigInteger: n) ! (in var bigInteger: k) is func
result
var bigInteger: binom is 0_;
Line 2,493 ⟶ 2,725:
end if;
end func;
</syntaxhighlight>
</lang>
 
Original source [http://seed7.sourceforge.net/algorith/math.htm#binomial_coefficient].
Line 2,500 ⟶ 2,732:
 
Simplest Solution:
<syntaxhighlight lang="sequencel">
<lang sequenceL>
choose(n, k) := product(k + 1 ... n) / product(1 ... n - k);
</syntaxhighlight>
</lang>
 
Tail-Recursive solution to avoid arithmetic with large integers:
<syntaxhighlight lang="sequencel">
<lang sequenceL>
 
choose(n,k) := binomial(n, k, 1, 1);
Line 2,512 ⟶ 2,744:
result when i > k else
binomial(n, k, i + 1, (result * (n - i + 1)) / i);
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
Straightforward translation of the formula:
<langsyntaxhighlight lang="ruby">func binomial(n,k) {
n! / ((n-k)! * k!)
}
 
say binomial(400, 200)</langsyntaxhighlight>
 
Alternatively, by using the ''Number.nok()'' method:
<syntaxhighlight lang ="ruby">say 400.nok(200)</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
Having a small language but a big class library in my bag, we can write:
<langsyntaxhighlight lang="smalltalk">Transcript showCR: (5 binco:3).
Transcript showCR: (400 binco:200)</langsyntaxhighlight>
{{out}}
<pre>10
Line 2,535 ⟶ 2,767:
 
A naïve implementation (in the Integer class) might look like:
<langsyntaxhighlight lang="smalltalk">binco:arg
^ (self factorial) / (arg factorial * (self-arg) factorial)</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="standardml">
fun binomial n k =
if k > n then 0 else
let fun f (_, 0) = 1
| f (i, d) = f (i + 1, d - 1) * i div d
in f (n - k + 1, k) end
</syntaxhighlight>
 
=={{header|Stata}}==
Use the [http://www.stata.com/help.cgi?comb comb] function. Notice the result is a missing value if k>n or k<0.
 
<langsyntaxhighlight lang="stata">. display comb(5,3)
10</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
Line 2,562 ⟶ 2,803:
 
print("binomial(\(5), \(3)) = \(binomial((5, 3)))")
print("binomial(\(20), \(11)) = \(binomial((20, 11)))")</langsyntaxhighlight>
 
{{out}}
Line 2,571 ⟶ 2,812:
=={{header|Tcl}}==
This uses exact arbitrary precision integer arithmetic.
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc binom {n k} {
# Compute the top half of the division; this is n!/(n-k)!
Line 2,587 ⟶ 2,828:
# Integer arithmetic divide is correct here; the factors always cancel out
return [expr {$pTop / $pBottom}]
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">puts "5_C_3 = [binom 5 3]"
puts "60_C_30 = [binom 60 30]"</langsyntaxhighlight>
{{Out}}
<pre>5_C_3 = 10
60_C_30 = 118264581564861424</pre>
 
=={{header|TI-57}}==
{| class="wikitable"
! Machine code
! Comment
|-
|
'''Lbl 9'''
STO 2
x⮂t
STO 1
SBR 0
STO 3
RCL 1
-
RCL 2
=
SBR 0
INV Prd 3
RCL 2
SBR 0
Inv Prd 3
RCL 3
R/S
RST
'''Lbl 0'''
C.t
x=t
1
STO 0
'''Lbl 1'''
RCL 0
×
Dsz
GTO 1
1
=
INV SBR
|
'''program binomial(x,t)''' // x is the display register
r2 = x
swap x and t
r1 = x
x = factorial(x)
r3 = x
x = r1 - r2
x = factorial(x)
r3 /= x
x = r2
x = factorial(x)
r3 /= x
x = r3
end program
reset pointer
'''program factorial(x)'''
t=0
if x=0 then
x=1
r0 = x
loop
multiply r0 by what will be in the next loop
decrement r0 and exit loop if r0 = 0
end loop
complete the multiplication sequence
return x!
end sub
|}
<code> 5 </code> <code>x⮂t</code> <code> 3 </code> <code>GTO</code> <code> 9 </code> <code>R/S</code>
{{out}}
<pre>
10.
</pre>
 
=={{header|TI-83 BASIC}}==
Builtin operator nCr gives the number of combinations.
<syntaxhighlight lang ="ti83b">10 nCr 4</langsyntaxhighlight>
{{out}}
<pre>
Line 2,607 ⟶ 2,924:
Builtin function.
 
<syntaxhighlight lang ="ti89b">nCr(n,k)</langsyntaxhighlight>
 
=={{header|TXR}}==
Line 2,613 ⟶ 2,930:
nCk is a built-in function, along with the one for permutations, nPk:
 
<langsyntaxhighlight lang="sh">$ txr -p '(n-choose-k 20 15)'
15504</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sh">$ txr -p '(n-perm-k 20 15)'
20274183401472000</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
 
<langsyntaxhighlight lang="sh">#!/bin/sh
n=5;
k=3;
Line 2,640 ⟶ 2,957:
binomial_coefficient=$(expr $n_factorial \/ $k_factorial \* 1 \/ $n_minus_k_factorial )
 
echo "Binomial Coefficient ($n,$k) = $binomial_coefficient"</langsyntaxhighlight>
 
=={{header|Ursala}}==
A function for computing binomial coefficients (<code>choose</code>) is included in a standard library, but if it weren't, it could be defined in one of the following ways, starting from the most idiomatic.
<langsyntaxhighlight Ursalalang="ursala">#import nat
 
choose = ~&ar^?\1! quotient^\~&ar product^/~&al ^|R/~& predecessor~~</langsyntaxhighlight>
The standard library functions <code>quotient</code>, <code>product</code> and <code>predecessor</code> pertain to natural numbers in the obvious way.
* <code>choose</code> is defined using the recursive conditional combinator (<code>^?</code>) as a function taking a pair of numbers, with the predicate <code>~&ar</code> testing whether the number on the right side of the pair is non-zero.
Line 2,656 ⟶ 2,973:
* The product of these values is then divided (<code>quotient</code>) by the right side (<code>~&ar</code>) of the original argument and returned as the result.
Here is a less efficient implementation more closely following the formula above.
<langsyntaxhighlight Ursalalang="ursala">choose = quotient^/factorial@l product+ factorial^~/difference ~&r</langsyntaxhighlight>
* <code>choose</code> is defined as the <code>quotient</code> of the results of a pair (<code>^</code>) of functions.
* The left function contributing to the quotient is the <code>factorial</code> of the left side (<code>@l</code>) of the argument, which is assumed to be a pair of natural numbers. The <code>factorial</code> function is provided in a standard library.
Line 2,664 ⟶ 2,981:
* A composition (<code>+</code>) of this function with the <code>product</code> function effects the multiplication of the two factorials, to complete the other input to the quotient.
Here is an equivalent implementation using pattern matching, dummy variables, and only the apply-to-both (<code>~~</code>) operator.
<langsyntaxhighlight Ursalalang="ursala">choose("n","k") = quotient(factorial "n",product factorial~~ (difference("n","k"),"k"))</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#cast %nL
 
main = choose* <(5,3),(60,30)></langsyntaxhighlight>
{{Out}}
<pre><10,118264581564861424></pre>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">Function binomial(n,k)
binomial = factorial(n)/(factorial(n-k)*factorial(k))
End Function
Line 2,693 ⟶ 3,010:
'calling the function
WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3)
WScript.StdOut.WriteLine</langsyntaxhighlight>
 
{{Out}}
Line 2,701 ⟶ 3,018:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
import "./math" for Int
 
var binomial = Fn.new { |n, k|
Line 2,727 ⟶ 3,044:
for (k in 0..n) System.write(Fmt.d(5, binomial.call(n, k)))
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 2,751 ⟶ 3,068:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code ChOut=8, CrLf=9, IntOut=11;
 
func Binomial(N, K);
Line 2,772 ⟶ 3,089:
CrLf(0);
];
] \Mr. Pascal's triangle!</langsyntaxhighlight>
 
{{Out}}
Line 2,788 ⟶ 3,105:
</pre>
 
=={{header|Zig}}==
A reasonable implementation for a fixed word size is to precompute all possible values of nCk, since even on a 64 bit machine there's only 67 rows of Pascal's triangle to consider, or ~18K of data.
 
In Zig it's possible to compute all values of nCk at compile time, so that at runtime it's only necessary to do a table lookup. Zig also supports nullable values, so nCk can return a null value if the programmer requests a value that's out of range. Finally, since this code uses addition to compute the table, all entries that can fit in 64 bits can be computed, in contrast to some other code examples that may overflow before the maximum representable value (67 choose 33) is reached. For example, the largest value the BCPL version can compute is 61 choose 31.
<syntaxhighlight lang="zig">
const std = @import("std");
 
pub fn binomial(n: u32) ?[]const u64 {
if (n >= rmax)
return null
else {
const k = n * (n + 1) / 2;
return pascal[k .. k + n + 1];
}
}
 
pub fn nCk(n: u32, k: u32) ?u64 {
if (n >= rmax)
return null
else if (k > n)
return 0
else {
const j = n * (n + 1) / 2;
return pascal[j + k];
}
}
 
const rmax = 68;
 
const pascal = build: {
@setEvalBranchQuota(100_000);
var coefficients: [(rmax * (rmax + 1)) / 2]u64 = undefined;
coefficients[0] = 1;
var j: u32 = 0;
var k: u32 = 1;
var n: u32 = 1;
while (n < rmax) : (n += 1) {
var prev = coefficients[j .. j + n];
var next = coefficients[k .. k + n + 1];
next[0] = 1;
var i: u32 = 1;
while (i < n) : (i += 1)
next[i] = prev[i] + prev[i - 1];
next[i] = 1;
j = k;
k += n + 1;
}
break :build coefficients;
};
 
test "n choose k" {
const expect = std.testing.expect;
try expect(nCk(10, 5).? == 252);
try expect(nCk(10, 11).? == 0);
try expect(nCk(10, 10).? == 1);
try expect(nCk(67, 33).? == 14226520737620288370);
try expect(nCk(68, 34) == null);
}
</syntaxhighlight>
Rather than write driver code, it's possible to run the unit test for this module.
{{Out}}
<pre>
$ zig test binomial.zig
All 1 tests passed.
</pre>
=={{header|zkl}}==
Using 64 bit ints:
<langsyntaxhighlight lang="zkl">fcn binomial(n,k){ (1).reduce(k,fcn(p,i,n){ p*(n-i+1)/i },1,n) }</langsyntaxhighlight>
{{out}}
<pre>
Line 2,801 ⟶ 3,183:
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<langsyntaxhighlight lang="zxbasic">10 LET n=33: LET k=17: PRINT "Binomial ";n;",";k;" = ";
20 LET r=1: LET d=n-k
30 IF d>k THEN LET k=d: LET d=n-k
Line 2,810 ⟶ 3,192:
80 GO TO 40
90 PRINT r
100 DEF FN m(a,b)=a-INT (a/b)*b</langsyntaxhighlight>
3,021

edits