What is nCr in mathematics?
nCr is referred to as the combination. nCr is a selection of r objects from a set of n objects.
Formula of nCr
nCr = n!/(r!*(n-r)!)
Find nCr through programming languages such as C, C++, and Java.
We will try to solve this problem with the help of functions. We need to create a function to find the factorial of n, r, and (n-r)! and then create a function to calculate the value of nCr.
Example of nCr
Input:
The value of n is 8
The value of r is 2
Output:
nCr = 28
Explanation:
The value of 8C2 is 28.
Code in C language
#include <stdio.h>
int factorial(int n){
int fact = 1;
for(int i=0; i<=n; i++){
fact = fact * i;
}
return fact;
}
int nCr(int n, int r){
int num = factorial(n);
int denom = factorial(r) * factorial(n-r);
int result = num/denom;
return result;
}
int main()
{
int n, r;
printf("The value of n is ");
scanf("%d", &n);
printf("The value of r is ");
scanf("%d", &r);
int result = nCr(n,r);
printf("%d",result);
return 0;
}
Output:
The value of n is 8
The value of r is 2
28
Code in C++ language
#include<iostream>
using namespace std;
int factorial(int n){
int fact = 1;
for(int i=0; i<=n; i++){
fact = fact * i;
}
return fact;
}
int nCr(int n, int r){
int num = factorial(n);
int denom = factorial(r) * factorial(n-r);
int result = num/denom;
return result;
}
int main()
{
int n, r;
cout << "The value of n is ";
cin>>n;
cout << "The value of r is ";
cin>>r;
int result = nCr(n,r);
cout<<result;
return 0;
}
Output:
The value of n is 8
The value of r is 2
28
Code in Java language
import java.util.Scanner;
public class Main
{
static int factorial(int n){
int fact = 1;
for(int i=0; i<=n; i++){
fact = fact * i;
}
return fact;
}
static int nCr(int n, int r){
int num = factorial(n);
int denom = factorial(r) * factorial(n-r);
int result = num/denom;
return result;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("The value of n is ");
int n = s.nextInt();
System.out.print("The value of r is ");
int r = s.nextInt();
int result = nCr(n,r);
System.out.println(result);
}
}
Output:
The value of n is 8
The value of r is 2
28
Task: Try to find the value of nPr
0 Comments