Download this source file


/*
 * Choose1.c - A program to calculate and print the value of
 * the choose function C(n, r).
 * This program uses an alternate method to compute C(n,r) which
 * allows it to compute larger values.  (But C(52, 13) still bombs!)
 * It also illustrates a fancy input technique.
 *
 * Written by Wayne Pollock,  2001 Tampa Florida USA.
 */

#include <stdio.h>

#define OK 1

/* P R O T O T Y P E S */

int check ( int n, int r );               /* Checks if r < n */
unsigned long choose ( int n, int r );    /* Computes C(n,r) */
unsigned long fact ( int top, int bot );  /* Computes a factor */

int main ( void )
{
   int n, r;
   char line[BUFSIZ], junk[BUFSIZ];

   fprintf( stderr, "Enter positive integers n and r: " );
   if ( fgets( line, sizeof(line), stdin ) == NULL )
   {  fprintf( stderr, "*** ERROR!  End Of File encountered!\a\n" );
      return -1;
   }
   if ( sscanf( line, "%i %i %s", &n, &r, junk ) != 2 )
   {  fprintf( stderr, "*** ERROR!  You must enter exactly 2 numbers,"
            " separated by white space!\a\n" );
      return -2;
   }
   if ( check( n, r ) != OK )
      return -3;
   printf( "C(%i,%i) = %lu.\n", n, r, choose( n, r ) );
   return 0;
}


int check ( int n, int r )
{
   if ( n < 0 || r < 0 )
   {  fprintf( stderr, "*** ERROR!  Numbers must be POSITIVE!\a\n" );
      return !OK;
   }
   if ( r > n )
   {  fprintf( stderr, "*** ERROR!  n must be as large or larger "
            "than r!\a\n" );
      return !OK;
   }
   return OK;
}


/* computes top*(top-1)*(top-2)*...*(bot+1) */
unsigned long fact ( int top, int bot )
{
   unsigned long result;

   for ( result=1; top>bot; --top )
   {  result *= top;
   }
   return result;
}

unsigned long choose ( int n, int r )
{
   if (n - r > r)
      return ( fact(n,n-r) / fact(r,1) );
   else
      return ( fact(n,r) / fact(n-r,1) );
}


/*
============================Output of Choose1.c============================

Enter positive integers n and r: 52 5
C(52,5) = 2598960.
*/




Send comments and mail to pollock@acm.org.