Number of combinations (N choose R) in C++

后端 未结 7 2429
日久生厌
日久生厌 2020-11-27 18:17

Here I try to write a program in C++ to find NCR. But I\'ve got a problem in the result. It is not correct. Can you help me find what the mistake is in the program?

7条回答
  •  被撕碎了的回忆
    2020-11-27 18:47

    Recursive function is used incorrectly here. fact() function should be changed into this:

    int fact(int n){
    if(n==0||n==1) //factorial of both 0 and 1 is 1. Base case.
    {
        return 1;
    }else
    
        return (n*fact(n-1));//recursive call.
    

    };

    Recursive call should be made in else part.

    NCR() function should be changed into this:

    int NCR(int n,int r){
        if(n==r) {
            return 1;
        } else if (r==0&&n!=0) {
            return 1;
        } else if(r==1)
        {
            return n;
        }
        else
        {
            return fact(n)/(fact(r)*fact(n-r));
        }
    };
    

提交回复
热议问题