Number of non-negative integral solutions of sum equation in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the number non-negative integral solution of sum equation.

The sum equation is x + y + z = n. You are given the number n, you need to find the number of solution for the equation.

Let's see the steps to solve the problem.

  • Initialise the number m.

  • Initialise the count to 0.

  • Write three nested loops to get all the combinations of three numbers.

    • Check the validation of the equation.

    • If the current numbers satisfies the equation, then increment the count.

  • Return the count.


Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getEquationSolutionCount(int n) {
   int count = 0;
   for (int i = 0; i <= n; i++) {
      for (int j = 0; j <= n - i; j++) {
         for (int k = 0; k <= n - i - j; k++) {
            if (i + j + k == n) {
   return count;
int main() {
   int n = 10;
   cout << getEquationSolutionCount(n) << endl;
   return 0;


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



If you have any queries in the tutorial, mention them in the comment section.

Published on 03-Jul-2021 08:21:10