📜  从N个男人中选择X个男人的总方法,包括或不包括某个特定男人

📅  最后修改于: 2021-06-25 16:52:07             🧑  作者: Mango

给定两个整数XN。任务是找到从N个男人中选择X个男人的总数,包括或不包括某个特定男人。
例子:

方法:N个人中选择X个人的总数为N C X

  • 包括一个特殊的人:我们可以从N – 1 C X – 1中的(N – 1)个中选择(X – 1)个男人
  • 扣除特定的人:我们可以选择从(N – 1)X战警中的N -图1C X

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the value of nCr
int nCr(int n, int r)
{
 
    // Initialize the answer
    int ans = 1;
 
    for (int i = 1; i <= r; i += 1) {
 
        // Divide simultaneously by
        // i to avoid overflow
        ans *= (n - r + i);
        ans /= i;
    }
    return ans;
}
 
// Function to return the count of ways
int total_ways(int N, int X)
{
    return (nCr(N - 1, X - 1) + nCr(N - 1, X));
}
 
// Driver code
int main()
{
    int N = 5, X = 3;
 
    cout << total_ways(N, X);
 
    return 0;
}


Java
// Java implementation of the approach
import java.io.*;
 
class GFG
{
     
// Function to return the value of nCr
static int nCr(int n, int r)
{
 
    // Initialize the answer
    int ans = 1;
 
    for (int i = 1; i <= r; i += 1)
    {
 
        // Divide simultaneously by
        // i to avoid overflow
        ans *= (n - r + i);
        ans /= i;
    }
    return ans;
}
 
// Function to return the count of ways
static int total_ways(int N, int X)
{
    return (nCr(N - 1, X - 1) + nCr(N - 1, X));
}
 
// Driver code
public static void main (String[] args)
{
    int N = 5, X = 3;
     
    System.out.println (total_ways(N, X));
}
}
 
// This code is contributed by Sachin


Python3
# Python3 implementation of the approach
 
# Function to return the value of nCr
def nCr(n, r) :
 
    # Initialize the answer
    ans = 1;
 
    for i in range(1, r + 1) :
 
        # Divide simultaneously by
        # i to avoid overflow
        ans *= (n - r + i);
        ans //= i;
 
    return ans;
 
# Function to return the count of ways
def total_ways(N, X) :
 
    return (nCr(N - 1, X - 1) + nCr(N - 1, X));
 
# Driver code
if __name__ == "__main__" :
 
    N = 5; X = 3;
 
    print(total_ways(N, X));
 
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
     
class GFG
{
     
// Function to return the value of nCr
static int nCr(int n, int r)
{
 
    // Initialize the answer
    int ans = 1;
 
    for (int i = 1; i <= r; i += 1)
    {
 
        // Divide simultaneously by
        // i to avoid overflow
        ans *= (n - r + i);
        ans /= i;
    }
    return ans;
}
 
// Function to return the count of ways
static int total_ways(int N, int X)
{
    return (nCr(N - 1, X - 1) + nCr(N - 1, X));
}
 
// Driver code
public static void Main (String[] args)
{
    int N = 5, X = 3;
     
    Console.WriteLine(total_ways(N, X));
}
}
     
// This code is contributed by 29AjayKumar


Javascript


输出:
10