DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Combinations.cpp

02.01.2008
| 1218 views |
  • submit to reddit
        #include <iostream>

using namespace std;

double factorial(long n)
{
 if (n==0)
   return 1;
 else
   return n*factorial(n-1);
}

double combination_0(int n, int k)
{
      return factorial(n)/factorial(n-k)/factorial(k);
}

double combination_1(int n, int k)
{
       double result = 1;
       while(k > 0)
       {
         result *= (double)(n--);
         result /= (double)(k--);
       } 
       return result;
}

double combination_r(int n, int k)
{
    if (k == 0)
      return 1;
    else
      return ((double)n/(double)k)*combination_r(n-1, k-1);
}

double power (int n, double p)
{
       if (n==0)
          return 1;
       else
       return p*power(n-1,p);
}

double binomial (int n, int k, double p)
{
       return combination_r(n,k)*power(k,p)*power(n-k,1-p);
}

double pi (int n)
{
       if(n==0)
         return 4;
       else
         if (n%2 == 0)
            return pi(n-1) + 4/(double)(2*n+1);
         else
            return pi(n-1) - 4/(double)(2*n+1);
}

main (void)
{
 int i;
 for (i=0; i<5; i++)
     cout << i << "! = " << factorial(i) << endl;
 cout << endl;
 cout << (int)combination_0(52,5) << endl;
 cout << (int)combination_1(52,5) << endl;
 cout << (int)combination_r(52,5) << endl << endl;
 cout << power(2,0.5) << endl;
 cout << binomial(3,2,0.5) << endl;
 for (i=0; i<1000200; i++)
   cout << i << " places " << pi(i) << endl;
 getchar();
}