📜  使用递归计算 nCr 值的程序

📅  最后修改于: 2022-05-13 01:56:09.070000             🧑  作者: Mango

使用递归计算 nCr 值的程序

给定两个数字Nr ,使用递归找到N C r的值

例子

方法:这个想法只是基于以下公式。

所以,

下面是上述方法的实现:

C++
// C++ code to implement above approach
#include 
using namespace std;
 
// Function to calculate the value of nCr
// using recursion
int nCr(int N, int r)
{
    int res = 0;
    if (r == 0) {
        return 1;
    }
    else {
        res = nCr(N, r - 1)
              * (N - r + 1) / r;
    }
    return res;
}
 
// Driver code
int main()
{
    int N = 5, r = 3;
    cout << nCr(N, r);
    return 0;
}


Java
// Java code for the above approach
import java.io.*;
class GFG {
 
  // Function to calculate the value of nCr
  // using recursion
  static int nCr(int N, int r)
  {
    int res = 0;
    if (r == 0) {
      return 1;
    }
    else {
      res = nCr(N, r - 1) * (N - r + 1) / r;
    }
    return res;
  }
 
  public static void main(String[] args)
  {
    int N = 5, r = 3;
 
    System.out.println(nCr(N, r));
  }
}
 
// This code is contributed by Potta Lokesh


Python3
# Python code to implement above approach
 
# Function to calculate the value Of nCr
# using recursion
def nCr(N, r):
    res = 0
    if(r == 0):
        return 1
    else:
        res = nCr(N, r-1)
* (N-r + 1) / r
    return res
 
 
# Driver code
if __name__ == "__main__":
    N = 5
    r = 3
    print(int(nCr(N, r)))


C#
using System;
 
public class GFG{
 
  // Function to calculate the value of nCr
  // using recursion
  static int nCr(int N, int r)
  {
    int res = 0;
    if (r == 0) {
      return 1;
    }
    else {
      res = nCr(N, r - 1)
        * (N - r + 1) / r;
    }
    return res;
  }
 
  // Driver code
  static public void Main (){
 
    int N = 5, r = 3;
    Console.WriteLine(nCr(N, r));
  }
}
 
// This code is contributed by hrithikgarg03188.


Javascript


输出
10

时间复杂度:O(N!)
辅助空间:O(1)