Number of integral solutions of the equation x1 + x2 +…. + xN = k in C++

C++Server Side ProgrammingProgramming

The solutions for the equation are

  • The number of non-negative integral solutions of the equation are $\left(\begin{array}{c}n-k+1\\ k\end{array}\right)$
  • The number of positive integral solutions of the equation are $\left(\begin{array}{c}k-1\\ n-1\end{array}\right)$

Add both to get the required answer. Let's see an example.

Input

n = 4
k = 7

Output

140

Algorithm

  • Initialise the numbers n and k.
  • Find the integral solutions of not-negative and positive numbers.
  • Add both of them.
  • Return the answer.

Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
int factorial(int n) {
   int product = 1;
   for (int i = 2; i <= n; i++) {
      product *= i;
   }
   return product;
}
int nCr(int n, int r) {
   return factorial(n) / (factorial(n - r) * factorial(r));
}
int main() {
   int n = 4;
   int k = 7;
   cout << nCr(n + k - 1, k) + nCr(k - 1, n - 1) &l<t; endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

140
raja
Published on 03-Jul-2021 05:33:19
Advertisements