Friday, July 31, 2009

I need help with programming the binomial coefficient in to C++? See my program below, what is not correct?

#include "stdafx.h" #include %26lt;iostream%26gt; using namespace std ; int binomial (int n, int k) ; // function prototype int main ()


{ int n, k ; // parameters for the binomial number int result ;


cout %26lt;%26lt; endl ; // read in n %26amp; k cout %26lt;%26lt; "Enter n (positive integer) : " ;


cin %26gt;%26gt; n ; cout %26lt;%26lt; "Enter k (positive integer) : " ; cin %26gt;%26gt; k ;


result = binomial (n,k); cout %26lt;%26lt; "Binomial number " %26lt;%26lt; n %26lt;%26lt; "C" %26lt;%26lt; k %26lt;%26lt; " = " %26lt;%26lt; result %26lt;%26lt; endl; return (0); }


int binomial (int n, int k)


Computes the binomial coefficient nCk


Inputes: n, k (integers)


Output: binomial coefficient nCk ( integer)


{ int numerator , denominator ;


int i ; // needed to compute numerator %26amp; denominator


if (n %26lt; k) { return (0) ; } else { denominator = k*(i+1) ; // initial value for (i=0; i%26lt;k+1; i++) denominator = i * denominator ;


numerator = n*(n-(k+i)) ; // initial value


for (numerator = 1 ; numerator %26lt; n ; numerator = n-(k+(i++)))


numerator =numerator*(n-k+(i++)) ; return (numerator / denominator) ; } // else }

I need help with programming the binomial coefficient in to C++? See my program below, what is not correct?
at least what wrong I can see are the following points:





1) if (n %26lt; k) { return (0) ; } else { denominator = k*(i+1)


You have not initialized i. So It can take any value and it gives you the wrong answer.


2) for (i=0; i%26lt;k+1; i++) denominator = i * denominator ;


When i = 0, denominator will be 0, and it remains 0 through out the loop!


3) numerator = n*(n-(k+i)) ; // initial value


After the loop above, i = k+1. Is it the right value that you want for the initial value of numerator?


No comments:

Post a Comment