Evaluate binomial coefficients: Difference between revisions

m
→‎{{header|REXX}}: added/changed whitespace and comments.
m (→‎{{header|REXX}}: added/changed whitespace and comments.)
Line 1,419:
The task is to compute ANY binomial coefficient(s), but these REXX examples are limited to 100k digits.
===idiomatic===
<lang rexx>/*REXX program calculates binomial coefficients (aka, combinations). */
numeric digits 100000 /*allowbe someable to handle gihugeic numbers. */
parse arg n k . /*get obtain N and K from the C.L. */
say 'combinations('n","k')=' comb(n,k) /*display the resultnumber toof terminalcombinations. */
exit /*stick a fork in it, we're all done. */
/*────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────COMB subroutine─────────────────────*/
comb: procedure; parse arg x,y; return fact!(x) % (fact!(x-y) * fact!(y))
/*────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────FACT subroutine─────────────────────*/
fact!: procedure; !=1; do j=2 to arg(1); !=!*j; end; return !</lang>
{{Out}}'''output''' when using the input of: &nbsp; <tt> 5 &nbsp; 3 </tt>
<pre>
combinations(5,3)= 10
</pre>
{{Out}}'''output''' when using the input of: &nbsp; <tt> 1200 &nbsp; 120 </tt>
<pre>
combinations(1200,120)= 1004576581793084916475353119318331966507299414258370667602185866686463289093457468590558508056798211449853806741873396451735444387513582540860551330127062642417424083600
Line 1,438:
 
===optimized===
This REXX version takes advantage of reducing the size (product) of the numerator, and also,
<br>and also, only two (factorial) products need be calculated.
<lang rexx>/*REXX program calculates binomial coefficients (aka, combinations). */
numeric digits 100000 /*allowbe someable to handle gihugeic numbers. */
parse arg n k . /*get obtain N and K from the C.L. */
say 'combinations('n","k')=' comb(n,k) /*display the resultnumber toof terminalcombinations. */
exit /*stick a fork in it, we're all done. */
/*────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────COMB subroutine─────────────────────*/
comb: procedure; parse arg x,y; return pfact(x-y+1,x) % pfact(2,y)
/*────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────PFACT subroutine────────────────────*/
pfact: procedure; !=1; do j=arg(1) to arg(2); !=!*j; end; return !</lang>
'''output''' is identical to the 1<sup>st</sup> version.<br>
 
It is (around average) about ten times faster than the 1<sup>st</sup> version for &nbsp; <code> 200,20 </code> &nbsp; and &nbsp; <code> 100,10</code>.
<br>For &nbsp; <code>100,80 </code> &nbsp; it is about 30% faster. <br>