Evaluate binomial coefficients: Difference between revisions
Content added Content deleted
m (→{{header|Tcl}}: Add comments) |
m (→{{header|Tcl}}: whitespace) |
||
Line 38: | Line 38: | ||
set pTop [expr {$pTop * $i}] |
set pTop [expr {$pTop * $i}] |
||
} |
} |
||
# Compute the bottom half of the division |
# Compute the bottom half of the division |
||
set pBottom 1 |
set pBottom 1 |
||
Line 43: | Line 44: | ||
set pBottom [expr {$pBottom * $i}] |
set pBottom [expr {$pBottom * $i}] |
||
} |
} |
||
# Integer arithmetic divide is correct here; the factors always cancel out |
# Integer arithmetic divide is correct here; the factors always cancel out |
||
return [expr {$pTop / $pBottom}] |
return [expr {$pTop / $pBottom}] |
Revision as of 00:29, 12 April 2010
Evaluate binomial coefficients
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
This programming task, is to calculate ANY binomial coefficient.
This formula is recommended: n!/k!(n-k)!
C++
<lang cpp>double Factorial(double nValue)
{ double result = nValue; double result_next; double pc = nValue; do { result_next = result*(pc-1); result = result_next; pc--; }while(pc>2); nValue = result; return nValue; }
double EvaluateBinomialCoefficient(double m_nValue, double nValue)
{ double result;
result = (Factorial(m_nValue))/(Factorial(nValue)*Factorial((m_nValue - nValue))); nValue = result; return nValue; }</lang>
Tcl
This uses exact arbitrary precision integer arithmetic. <lang tcl>package require Tcl 8.5 proc binom {n k} {
# Compute the top half of the division set pTop 1 for {set i $n} {$i > $n - $k} {incr i -1} {
set pTop [expr {$pTop * $i}]
}
# Compute the bottom half of the division set pBottom 1 for {set i $k} {$i > 1} {incr i -1} {
set pBottom [expr {$pBottom * $i}]
}
# Integer arithmetic divide is correct here; the factors always cancel out return [expr {$pTop / $pBottom}]
}</lang> Demonstrating: <lang tcl>puts "60_C_30 = [binom 60 30]"</lang> Output:
60_C_30 = 118264581564861424