Program to calculate value of nCr
Given two numbers N and r, The task is to find the value of NCr . Combinations represent the number of ways to choose r elements from a set of n distinct elements, without regard to the order in which they are selected. The formula for calculating combinations is :
C(n,r) = n! / r! * (n-r) !
Where :
- (n!) represents the factorial of n .
- (r!) represents the factorial of r .
Examples :
Input: N = 5, r = 2
Output: 10
Explanation: The value of 5C2 is 10Input: N = 3, r = 1
Output: 3
Program to Calculate the value of nCr
Approach 1 : Using Factorial
The total number of ways for selecting r elements out of n options are nCr = (n!) / (r! * (n-r)!)
where n! = 1 * 2 * . . . * n.
Below is the Implementation of the above approach:
// CPP program To calculate The Value Of nCr
#include <bits/stdc++.h>
using namespace std;
long nCr(int n, int r)
{
return fact(n) / (fact(r) * fact(n - r));
}
// Returns factorial of n
long fact(int n)
{
if(n==0)
return 1;
long res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
// Driver code
int main()
{
int n = 5, r = 3;
cout << nCr(n, r);
return 0;
}
#include <stdio.h>
long factorial(int n) {
if(n == 0 || n==1)
return 1;
long factorial = 1;
for (int i = 2; i <= n; i++)
factorial = factorial * i;
return factorial;
}
long nCr(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n - r));
}
int main() {
int n = 5, r = 3;
printf("%d", nCr(n, r));
return 0;
}
// This code was contributed by Omkar Prabhune
// Java program To calculate
// The Value Of nCr
import java.io.*;
public class GFG {
static long nCr(int n, int r)
{
return fact(n) / (fact(r) *
fact(n - r));
}
// Returns factorial of n
static long fact(int n)
{
if(n==0 || n==1)
return 1;
long res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
// Driver code
public static void main(String[] args)
{
int n = 5, r = 3;
System.out.println(nCr(n, r));
}
}
// This code is Contributed by
// Smitha Dinesh Semwal.
# Python 3 program To calculate
# The Value Of nCr
def nCr(n, r):
return (fact(n) / (fact(r)
* fact(n - r)))
# Returns factorial of n
def fact(n):
if n == 0 or n==1:
return 1
res = 1
for i in range(2, n+1):
res = res * i
return res
# Driver code
n = 5
r = 3
print(int(nCr(n, r)))
# This code is contributed
# by Smitha and improved by naveenkumar30838
// C# program To calculate
// The Value Of nCr
using System;
class GFG {
static long nCr(int n, int r)
{
return fact(n) / (fact(r) *
fact(n - r));
}
// Returns factorial of n
static long fact(int n)
{
if(n==0 || n==1)
return 1;
long res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
// Driver code
public static void Main()
{
int n = 5, r = 3;
Console.Write(nCr(n, r));
}
}
// This code is Contributed by nitin mittal and improved by naveenkumar30838
<script>
// Javascript program To calculate The Value Of nCr
function nCr(n, r)
{
return fact(n) / (fact(r) * fact(n - r));
}
// Returns factorial of n
function fact(n)
{
if(n==0 || n==1)
return 1;
var res = 1;
for (var i = 2; i <= n; i++)
res = res * i;
return res;
}
// Driver code
var n = 5, r = 3;
document.write(nCr(n, r));
</script>
<?php
// PHP program To calculate
// the Value Of nCr
function nCr( $n, $r)
{
return fact($n) / (fact($r) *
fact($n - $r));
}
// Returns factorial of n
function fact( $n)
{
if($n == 0 || $n==1)
return 1;
$res = 1;
for ( $i = 2; $i <= $n; $i++)
$res = $res * $i;
return $res;
}
// Driver code
$n = 5;
$r = 3;
echo nCr($n, $r);
// This code is contributed by vt_m.
?>
Output
10
Time Complexity: O(N)
Auxiliary Space: O(1)
Complexity Analysis:
The time complexity of the above approach is O(N).
This is because the function fact() has a time complexity of O(N), and it is called twice for each call to nCr().
The space complexity of the above approach is O(1).
Because the function does not make any recursive calls and only uses a constant amount of memory.
Approach 2 : Using Recursion
The idea is to use a recursive function to calculate the value of nCr. The base cases are:
- if r is greater than n, return 0 (there are no combinations possible)
- if r is 0 or r is n, return 1 (there is only 1 combination possible in these cases)
For other values of n and r, the function calculates the value of nCr by adding the number of combinations possible by including the current element and the number of combinations possible by not including the current element.
Below is the Implementation of the above approach:
#include <iostream>
using namespace std;
int nCr(int n, int r)
{
if (r > n)
return 0;
if (r == 0 || r == n)
return 1;
return nCr(n - 1, r - 1) + nCr(n - 1, r);
}
int main()
{
cout << nCr(5, 3); // Output: 10
return 0;
}
// This code is contributed by Susobhan Akhuli
import java.util.*;
class GFG {
public static int nCr(int n, int r)
{
if (r > n)
return 0;
if (r == 0 || r == n)
return 1;
return nCr(n - 1, r - 1) + nCr(n - 1, r);
}
public static void main(String[] args)
{
System.out.println(nCr(5, 3)); // Output: 10
}
}
// This code is contributed by Prasad Kandekar(prasad264)
def nCr(n, r):
if r > n:
return 0
if r == 0 or r == n:
return 1
return nCr(n-1, r-1) + nCr(n-1, r)
print(nCr(5, 3)) # Output: 10
# This code is contributed by Susobhan Akhuli
using System;
public class GFG {
static public int nCr(int n, int r)
{
if (r > n)
return 0;
if (r == 0 || r == n)
return 1;
return nCr(n - 1, r - 1) + nCr(n - 1, r);
}
static public void Main(string[] args)
{
Console.WriteLine(nCr(5, 3)); // Output: 10
}
}
// This code is contributed by Prasad Kandekar(prasad264)
function nCr(n, r) {
if (r > n)
return 0;
if (r === 0 || r === n)
return 1;
return nCr(n-1, r-1) + nCr(n-1, r);
}
console.log(nCr(5, 3)); // Output: 10
// This code is contributed by Prasad Kandekar(prasad264)
Output
10
Time Complexity: O(2N)
Auxiliary Space: O(N2)
Approach 3 : Using Binomial Coefficient formula
- A binomial coefficient C(n, k) can be defined as the coefficient of Xk in the expansion of (1 + X)n.
- A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can be chosen from among n objects; more formally, the number of k-element subsets (or k-combinations) of an n-element set.
Iterative way of calculating NCR. using binomial coefficient formula.
#include <iostream>
using namespace std;
int main() {
int n = 5;
int r = 2;
double sum = 1;
// Calculate the value of n choose r using the binomial coefficient formula
for(int i = 1; i <= r; i++){
sum = sum * (n - r + i) / i;
}
cout<<(int)sum<<endl;
return 0;
}
import java.util.*;
public class BinomialCoefficient {
public static void main(String[] args)
{
int n = 5;
int r = 2;
double sum = 1;
// Calculate the value of n choose r using the
// binomial coefficient formula
for (int i = 1; i <= r; i++) {
sum = sum * (n - r + i) / i;
}
// Print the result after converting it to an
// integer
System.out.println((int)sum);
}
}
n = 5
r = 2
sum = 1
# Calculate the value of n choose r using the binomial coefficient formula
for i in range(1, r+1):
sum = sum * (n - r + i) / i
print(int(sum))
# This code is contributed by divyansh2212
using System;
// C# code implementation
class HelloWorld {
static void Main() {
int n = 5;
int r = 2;
double sum = 1;
// Calculate the value of n choose r using the binomial coefficient formula
for(int i = 1; i <= r; i++){
sum = sum * (n - r + i) / i;
}
Console.WriteLine((int)sum);
}
}
// The code is contributed by Arushi jindal.
let n = 5;
let r = 2;
let sum = 1;
// Calculate the value of n choose r using the binomial coefficient formula
for(let i = 1; i <= r; i++){
sum = sum * (n - r + i) / i;
}
console.log(Math.floor(sum));
// This code is contributed by prasad264
Output
10
Time complexity : O(r)
Space complexity : O(1)
Approach 4 : Using Logarithmic Formula
Logarithmic formula for nCr is an alternative to the factorial formula that avoids computing factorials directly and it’s more efficient for large values of n and r. It uses the identity log(n!) = log(1) + log(2) + … + log(n) to express the numerator and denominator of the nCr in terms of sums of logarithms which allows to calculate the nCr using the Logarithmic operations. This approach is faster and very efficient.
The logarithmic formula for nCr is:
nCr = exp( log(n!) – log(r!) – log((n-r)!) )
Below is the implementation of above approach:
#include <bits/stdc++.h>
using namespace std;
// Calculates the binomial coefficient nCr using the logarithmic formula
int nCr(int n, int r) {
// If r is greater than n, return 0
if (r > n) return 0;
// If r is 0 or equal to n, return 1
if (r == 0 || n == r) return 1;
// Initialize the logarithmic sum to 0
double res = 0;
// Calculate the logarithmic sum of the numerator and denominator using loop
for (int i = 0; i < r; i++) {
// Add the logarithm of (n-i) and subtract the logarithm of (i+1)
res += log(n-i) - log(i+1);
}
// Convert logarithmic sum back to a normal number
return (int)round(exp(res));
}
int main() {
// Calculate nCr for n = 5 and r = 2
int n = 5;
int r = 2;
cout << nCr(n, r) << endl;
return 0;
}
import java.util.*;
public class GFG {
// Calculates the binomial coefficient nCr using the logarithmic formula
static int nCr(int n, int r) {
// If r is greater than n, return 0
if (r > n)
return 0;
// If r is 0 or equal to n, return 1
if (r == 0 || n == r)
return 1;
// Initialize the logarithmic sum to 0
double res = 0;
// Calculate the logarithmic sum of the numerator and denominator using loop
for (int i = 0; i < r; i++) {
// Add the logarithm of (n-i) and subtract the logarithm of (i+1)
res += Math.log(n - i) - Math.log(i + 1);
}
// Convert logarithmic sum back to a normal number
return (int) Math.round(Math.exp(res));
}
public static void main(String[] args) {
// Calculate nCr for n = 5 and r = 2
int n = 5;
int r = 2;
System.out.println(nCr(n, r));
}
}
import math
# Calculates the binomial coefficient nCr using the logarithmic formula
def nCr(n, r):
# If r is greater than n, return 0
if r > n:
return 0
# If r is 0 or equal to n, return 1
if r == 0 or n == r:
return 1
# Initialize the logarithmic sum to 0
res = 0
# Calculate the logarithmic sum of the numerator and denominator using loop
for i in range(r):
# Add the logarithm of (n-i) and subtract the logarithm of (i+1)
res += math.log(n-i) - math.log(i+1)
# Convert logarithmic sum back to a normal number
return round(math.exp(res))
# Test case
n = 5
r = 2
print(nCr(n, r))
using System;
namespace BinomialCoefficient
{
class Program
{
// Calculates the binomial coefficient nCr using the logarithmic formula
static int nCr(int n, int r)
{
// If r is greater than n, return 0
if (r > n) return 0;
// If r is 0 or equal to n, return 1
if (r == 0 || n == r) return 1;
// Initialize the logarithmic sum to 0
double res = 0;
// Calculate the logarithmic sum of the numerator and denominator using loop
for (int i = 0; i < r; i++)
{
// Add the logarithm of (n-i) and subtract the logarithm of (i+1)
res += Math.Log(n - i) - Math.Log(i + 1);
}
// Convert logarithmic sum back to a normal number
return (int)Math.Round(Math.Exp(res));
}
static void Main(string[] args)
{
// Calculate nCr for n = 5 and r = 2
int n = 5;
int r = 2;
Console.WriteLine(nCr(n, r));
}
}
}
// Calculates the binomial coefficient nCr using the logarithmic formula
function nCr(n, r) {
// If r is greater than n, return 0
if (r > n) return 0;
// If r is 0 or equal to n, return 1
if (r === 0 || n === r) return 1;
// Initialize the logarithmic sum to 0
let res = 0;
// Calculate the logarithmic sum of the numerator and denominator using loop
for (let i = 0; i < r; i++) {
// Add the logarithm of (n-i) and subtract the logarithm of (i+1)
res += Math.log(n - i) - Math.log(i + 1);
}
// Convert logarithmic sum back to a normal number
return Math.round(Math.exp(res));
}
// Test case
const n = 5;
const r = 2;
console.log(nCr(n, r));
Output
10
Time Complexity: O(r)
Auxiliary Space: O(1)
Approach 5 : Using Efficient Computation of Combinations
The formula for nCr is = n! / r! * (n-r) ! . Let’s imagine r > n-r (or can take reverse ) . Logic here is since in n! and r! we are going to calculate the factorial of r numbers twice and which is no use i.e they will just cancel out each other , so we don’t calculate them instead we would calculate the product of number from (r , n] and product of numbers from 1 to n-r and divide them (here r can be imagined as the maximum of r , n-r ) . Below is the code for above implementation
#include <iostream>
// calculate multiplication of natural numbers from start to end
double Multiplier(int start, int end)
{
if (start == end) {
return start;
}
else {
double res = 1;
while (start <= end) {
res *= start;
start++;
}
return res;
}
}
double nCR(int n, int r)
{
if (n < r) {
return -1;
}
else if (n == r || r == 0) {
return 1;
}
else {
int max_val = std::max(r, n - r);
int min_val = std::min(r, n - r);
double numerator = Multiplier(max_val + 1, n);
double denominator = Multiplier(1, min_val);
return numerator / denominator;
}
}
int main()
{
int n = 20005;
int r = 25;
std::cout << nCR(n, r) << std::endl;
return 0;
// contributed by Naveen (naveenkumar30838)
}
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static double nCR(int n, int r)
{
if (n < r) {
return -1;
}
if (n == r || r == 0) {
return 1;
}
int max = Math.max(r, n - r);
int min = Math.min(r, n - r);
return (double)(Multiplier(max + 1, n)
/ Multiplier(1, min));
}
// calculate multiplication of natural numbers from start to end
public static double Multiplier(int start, int end)
{
if (start == end) {
return start;
}
double res = 1;
while (start <= end) {
res *= start;
start++;
}
return res;
}
public static void main(String[] args)
{
System.out.println(
nCR(20005, 25)); // ans 2.1443850196899737E82
// Code contributed by Naveen (naveenkumar30838)
}
}
def nCR(n, r):
if n < r:
return -1
if n == r or r == 0:
return 1
max_val = max(r, n - r)
min_val = min(r, n - r)
return Multiplier(max_val + 1, n) / Multiplier(1, min_val)
# calculate multiplication of natural numbers from start to end
def Multiplier(start, end):
if start == end:
return start
res = 1
while start <= end:
res *= start
start += 1
return res
print(nCR(20005, 25))
#contributed by Naveen (naveenkumar30838)
# ans 21443850196899739431852611539526726818562627337667639676891232267646561961531437300
using System;
class GFG {
static double nCR(int n, int r)
{
if (n < r) {
return -1;
}
else if (n == r || r == 0) {
return 1;
}
else {
int max_val = Math.Max(r, n - r);
int min_val = Math.Min(r, n - r);
double numerator = Multiplier(max_val + 1, n);
double denominator = Multiplier(1, min_val);
return numerator / denominator;
}
}
// calculate multiplication of natural numbers from start to end
static double Multiplier(int start, int end)
{
if (start == end) {
return start;
}
else {
double res = 1;
while (start <= end) {
res *= start;
start++;
}
return res;
}
}
static void Main(string[] args)
{
int n = 20005;
int r = 25;
Console.WriteLine($ "{nCR(n, r)}");
// Contributed by Naveen(naveenkumar30838)
// ans 2.1443850196899737E82
}
}
// Calculate multiplication of natural numbers from start to end
function multiplier(start, end) {
if (start === end) {
return start;
} else {
let res = 1;
while (start <= end) {
res *= start;
start++;
}
return res;
}
}
// Function to calculate n choose r (nCr)
function nCR(n, r) {
if (n < r) {
return -1;
} else if (n === r || r === 0) {
return 1;
} else {
const maxVal = Math.max(r, n - r);
const minVal = Math.min(r, n - r);
const numerator = multiplier(maxVal + 1, n);
const denominator = multiplier(1, minVal);
return numerator / denominator;
}
}
// Example usage
const n = 20005;
const r = 25;
console.log(nCR(n, r));
Output : 2.1443850196899737E82
Time complexity : O(n)
Space complexity : O(1)
Complexity Analysis : In every case (including worst case ) we have to calculate the multiplier from (n-r) and from (1 to r ) which give run in linear time giving a total time complexity of O(n-r +r ) = O(n) . Since no extra space is used so space complexity if O(1) . Since we have eliminated the repeated steps so it is a more optimized solution and hence it can be used for handling large values .
Conclusion
In conclusion, nCr can be efficiently computed using several approaches, including factorial computation, recursion, binomial coefficient formula, logarithmic formula, and an optimized method that eliminates redundant calculations. Each approach has its own time and space complexity considerations, with the optimized solution being particularly suitable for handling large values due to its linear time complexity and constant space complexity. Additionally, further exploration of dynamic programming techniques and space-time efficient binomial coefficient calculations offer more efficient solutions for handling complex scenarios .
Contact Us