Search code examples
c++binomial-coefficients

CPP - Binomial Coefficient - i get wrong results


Task: Write and test a C++ function that computes binomial coefficients. Three Definitions of the Binomial Coefficients are given (see picture below). I personally used the middle one definition.

My problem: But the Problem is, that I'm getting wrong results. 5 over 2 must be 10 I get 26 instead.

Why not other Definitions of Binomial Coefficient? Because in the other two there is in each definition a fraction and I'm afraid of getting rounding errors by doing divisoin in C++. That's why I chose the Definition in the middle.

My Code:

    #include <iostream>


int binomial(int a,int b){
  if(a < b) return 0;
  else if(a == b || a == 0 ) return 1;

  return binomial(a-1,b) + binomial(a-1,b-1);
}




int main(){

int n; 
int k;
std::cin >> n;
std::cin >> k;

std::cout << "Binomial of " << n << " and " << k << " equals = " << binomial(n,k) << std::endl;

  return 0;
}

Three Definitions of Binomial Coefficient given: Three Definitions of Binomial Coefficient


Solution

  • You have the second case wrong

    int binomial(int a,int b){
      if(a < b) return 0;
      else if(a == b || a == 0 ) return 1;   //  <------------
    
      return binomial(a-1,b) + binomial(a-1,b-1);
    }
    

    The formula says "if n=k or k=0" and in your code a == n and b == k, so that second line should be

    else if(a == b || b == 0 ) return 1;
    

    Note that better naming could have prevented that mistake.

    PS

    Why not other Definitions of Binomial Coefficient?

    Your reasoning is correct for the last definition, but not for the first. The result is always an integer, hence the nominator and denominator are always such that you can carry out the division using integer arithmetics. You will rather run into a problem with getting unnecessarily huge terms for the factorial.