Program to print the permutation (nPr) of the given number Permutation
Formula :
nPr=n!/(n-r)!=n(n-1) (n-2)(n-3).....(n-r+1)
n!= n (n-1)(n-2)(n-3)....3.2.1
Example 1:
Input: n = 5, r=2
Output: 20// i.e 5!=5*4*3*2*1=120, !(5-2)=!3=3*2*1=6, 120/6=20
Approach:
Java
public class NPR {public static void main(String[] args) {int n = 5;int r = 2;int npr = nPr(n, r);System.out.println(npr);}// calculate the nPrprivate static int nPr(int n, int r) {// formula: fact(n) / fact (n-r)return factorialR(n) / factorialR(n - r);}// factorialprivate static int factorialR(int num) {if (num == 1)return num;return num * factorialR(num - 1);}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the factorial//of given numberint factorialR(int num){//base caseif (num == 1)return num;return num * factorialR(num - 1);}//function to calculate the nPrint nPr(int n, int r){// formula: fact(n) / fact (n-r)return factorialR(n) / factorialR(n - r);}int main(){int n = 5;int r = 2;int npr = nPr(n, r);cout<<npr<<"\n";return 0;}
No comments:
Post a Comment