SOURCE FILE: nChooseB.cpp


/* 

This is a little program that exercises a NON-recursive
   function that calculates N choose K. 

The idea is to use the formula (N choose K) = N(N-1)...(N-K+1)/K(K-1)...(1)
= [N/K][(N-1)/(K-1)]...[(N-K+1)/(1)] -- which is a product of just K terms.

We also exploit the fact that (N choose K) equals (N choose N-K)
to keep the number of terms down to no more than N/2.

For example, we would calculate [10 choose 7] like this:  First
note that 7 is more than half 10 so it will be less work to
calculate the desired number as [10 choose 3] which is figured as
(10/3)*(9/2)*(8/1) = 120

*/

#include <iostream.h>
#include <iomanip.h>

double chooseB (int N, int K)
{
  double n=N, k=K ;
  if ( k > (n/2)) k = n-k ;
  int cnt ; double res = 1 ;
  for (cnt=1; cnt <= k; cnt++) res *= (n-k+cnt)/cnt ;
  return res ;
}

int main ()
{
  cout.setf(ios::fixed) ;
//  cout.setf(ios::showpoint) ;
  cout << setprecision(0) ;
  cout << "10 Choose 5 is: " << chooseB(10,5) << endl ;
  cout << "20 Choose 10 is: " << chooseB(20,10) << endl ;
  cout << "22 Choose 11 is: " << chooseB(22,11) << endl ;
  cout << "24 Choose 12 is: " << chooseB(24,12) << endl ;
  cout << "26 Choose 13 is: " << chooseB(26,13) << endl ;
  cout << "28 Choose 14 is: " << chooseB(28,14) << endl ;
  cout << "30 Choose 15 is: " << chooseB(30,15) << endl ;
  cout << "40 Choose 20 is: " << chooseB(40,20) << endl ;
  cout << "50 Choose 25 is: " << chooseB(50,25) << endl ;
  cout << "60 Choose 30 is: " << chooseB(60,30) << endl ;
  cout << "70 Choose 35 is: " << chooseB(70,35) << endl ;
  return 0 ;
}