Monday, 16 June 2014

C++ program to find nCr

Here is a C++ program to find ncr by simple method and than by recursion.
Formula for nCr = n!/(r!*(n-r)!).
Recursive formula nCr = (n-1)Cr + (n-1)C(r-1)

Method 1 : C++ program to calculate nCr
#include <iostream>
using namespace std;
long factorial(long);
int main()
{
    long n,r,ncr;
    cout<<"Enter the value of n and r ";
    cin>>n>>r;
    ncr=factorial(n)/(factorial(r)*factorial(n-r));
    cout<<"nCr = "<<ncr;
    return 0;
}
long factorial(long number)
{
    long fact=1;
    while(number!=0)
    {
        fact*=number;
        number--;
    }
    return fact;
}




Method 2 : C++ program to calculate nCr using recursion
#include<iostream>
#include<math.h>
using namespace std;
int ncr(int n,int r)
{
    if(r==0||n==r)
        return 1;
    return ncr(n-1,r-1)+ncr(n-1,r);
}
int main()
{
    int n,r;
    cout<<"Enter the value of n and r : ";
    cin>>n>>r;
    if(n<r)
        cout<<"r should be less than n ";
    cout<<"nCr = "<<ncr(n,r);
    return 0;
}

No comments:

Post a Comment