Total ways of selecting a group of X men from N men with or without including a particular man
Given two integers X and N. The task is to find the total number of ways of selecting X men from a group of N men with or without including a particular man.
Examples:
Input: N = 3 X = 2
Output: 3
Including a man say M1, the ways can be (M1, M2) and (M1, M3).
Excluding a man say M1, the only way is (M2, M3).
Total ways = 2 + 1 = 3.
Input: N = 5 X = 3
Output: 10
Approach: The total number of ways of choosing X men from N men is NCX
- Including a particular man: We can choose (X – 1) men from (N – 1) in N – 1CX – 1.
- Excluding a particular man: We can choose X men from (N – 1) in N – 1CX
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int nCr( int n, int r)
{
int ans = 1;
for ( int i = 1; i <= r; i += 1) {
ans *= (n - r + i);
ans /= i;
}
return ans;
}
int total_ways( int N, int X)
{
return (nCr(N - 1, X - 1) + nCr(N - 1, X));
}
int main()
{
int N = 5, X = 3;
cout << total_ways(N, X);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int nCr( int n, int r)
{
int ans = 1 ;
for ( int i = 1 ; i <= r; i += 1 )
{
ans *= (n - r + i);
ans /= i;
}
return ans;
}
static int total_ways( int N, int X)
{
return (nCr(N - 1 , X - 1 ) + nCr(N - 1 , X));
}
public static void main (String[] args)
{
int N = 5 , X = 3 ;
System.out.println (total_ways(N, X));
}
}
|
Python3
def nCr(n, r) :
ans = 1 ;
for i in range ( 1 , r + 1 ) :
ans * = (n - r + i);
ans / / = i;
return ans;
def total_ways(N, X) :
return (nCr(N - 1 , X - 1 ) + nCr(N - 1 , X));
if __name__ = = "__main__" :
N = 5 ; X = 3 ;
print (total_ways(N, X));
|
C#
using System;
class GFG
{
static int nCr( int n, int r)
{
int ans = 1;
for ( int i = 1; i <= r; i += 1)
{
ans *= (n - r + i);
ans /= i;
}
return ans;
}
static int total_ways( int N, int X)
{
return (nCr(N - 1, X - 1) + nCr(N - 1, X));
}
public static void Main (String[] args)
{
int N = 5, X = 3;
Console.WriteLine(total_ways(N, X));
}
}
|
Javascript
<script>
function nCr(n, r)
{
let ans = 1;
for (let i = 1; i <= r; i += 1) {
ans *= (n - r + i);
ans /= i;
}
return ans;
}
function total_ways(N, X)
{
return (nCr(N - 1, X - 1) + nCr(N - 1, X));
}
let N = 5, X = 3;
document.write(total_ways(N, X));
</script>
|
Time Complexity: O(X)
Auxiliary Space: O(1)
Last Updated :
13 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...