Monday, 16 June 2014

C++ program to find nPr

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


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




Method 2 : C++ program to calculate nPr using recursion
#include<iostream>
#include<math.h>
using namespace std;
int ncr(int n,int r)
{
    if(r==0)
        return 1;
    return ncr(n-1,r-1)*n;
}
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<<"nPr = "<<ncr(n,r);
    return 0;
}

No comments:

Post a Comment