Jump to content

Evaluate binomial coefficients: Difference between revisions

→‎{{header|Perl 6}}: various rephrasings
(→‎{{header|Perl 6}}: using a symmetry property)
(→‎{{header|Perl 6}}: various rephrasings)
Line 1,333:
 
=={{header|Perl 6}}==
For a start, you can get the length of the corresponding list of combinations:
<lang perl6>sub infix:<choose> { [*] ($^n ... 0) Z/ 1 .. $^p }
<lang perl6>say combinations(5, 3).elems;
say 5 choose 3;</lang>
{{out}}
<pre>10</pre>
 
This method is efficient, as Perl 6 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:
A useful optimization would use a symmetry property of the binomial coefficient:
 
<lang perl6>sub infix:<choose> { [*] ($^n ... 0) Z/ 1 .. $^p }</lang>
 
A usefulpossible optimization would use a symmetry property of the binomial coefficient:
 
<lang perl6>sub infix:<choose> { [*] ($^n ... 0) Z/ 1 .. min($n - $^p, $p) }</lang>
 
One drawback of this method is that it returns a Rat, not an Int. IfSo we reallyactually worrymay aboutwant it, we canto enforce the conversion:
<lang perl6>sub infix:<choose> { ([*] ($^n ... 0) Z/ 1 .. min($n - $^p, $p)).Int }</lang>
 
And ''this'' is exactly what the <tt>count-only</tt> method does.
 
=={{header|PL/I}}==
1,935

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.