Program to print the permutation (nCr) of the given number Permutation
Formula :
nCr = [n(n-1) ... (n-r+1)] / r(r-1)...1
nCr = fact(n) / (fact(r)*fact (n-r))
Example 1:
Input: n = 5, r=2
Output: 10// i.e 5!=5*4*3*2*1=120, !(5-2)=!3=3*2*1=6, !2=2*!=2 120/6*2=10
Approach:
Java
public class NCR {public static void main(String[] args) {int n = 5;int r = 2;int ncr = nCr(n, r);System.out.println(ncr);}// calculate the nCrprivate static int nCr(int n, int r) {// formula: fact(n) / (fact(r)*fact (n-r))int nfact = factorialR(n);int rfact = factorialR(r);int rnfact = factorialR(n - r);return nfact / (rfact * rnfact);}// 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 a given numberint factorialR(int num){//base caseif (num == 1)return num;return num * factorialR(num - 1);}//function to calculate the nCrint nCr(int n, int r){// formula: fact(n) / (fact(r)*fact (n-r))int nfact = factorialR(n);int rfact = factorialR(r);int rnfact = factorialR(n - r);return nfact / (rfact * rnfact);}int main(){int n = 5;int r = 2;int ncr = nCr(n, r);cout<<ncr<<"\n";return 0;}
No comments:
Post a Comment