Find the Number of solutions for the equation x + y + z <= n using C++


In this article, we will explain the approaches to find the number of solutions for the equation x+y+z<=n. In this problem, we have an equation with four variables, and the task is to find the solution for the given equation. So here is a simple example &miuns;

Input: X = 1, Y = 1, Z = 1, n = 1

Output: 4

Input: X = 1, Y = 2, Z = 3, n = 4

Output: 3

In this problem, we can simply go through all the values of (x, y), (y,z), (x,z) by isolating each variable and checking if it satisfies the equation or not.

Approach to Find the Solution

Now we will use the Brute Force approach to find the solution to the given problem.

Brute Force

In this program we are going to go through all the possible values of (x,y), (y,z) and (x,z) such that it satisfies the equation z <= n - x - y (here z is isolated) where 0 <= z <= Z (and same for other isolated variables).

Example


#include<bits/stdc++.h>
using namespace std;
int main(){
    int X = 1, Y = 2, Z = 3, n = 4; // limits of x, y, z and given n.
    int answer = 0; // counter variable.
    for(int i = 0; i <= X; i++){
        for(int j = 0; j <= Y; j++){
            int temp = (n - i) - j; // temp = n - x - y.
            if(temp >= Z){ // if n - x - y >= z so we increment the answer.
               answer++;
            }
        }
    }
    for(int i = 0; i <= X; i++){
        for(int j = 0; j <= Z; j++){
            int temp = (n - i) - j; // temp = n - x - y.
            if(temp >= Y){ // if n - x - y >= z so we increment the answer.
               answer++;
            }
        }
    }
    for(int i = 0; i <= Z; i++){
        for(int j = 0; j <= Y; j++){
            int temp = (n - i) - j; // temp = n - x - y.
            if(temp >= X){ // if n - x - y >= z so we increment the answer.
               answer++;
            }
        }
    }
    cout << answer << "\n";
}

Output

17

Explanation of the Above Program

In this program, we are going to go through all the combinations of (x,y), (y, z), (x,z) using a nested for loop and check the equation if it satisfies the equation or not and if it satisfies then, we increment the answer.

Conclusion

In this article, we solve a problem finding the Number of solutions that satisfy the equation x + y + z<= n in O(X*Y) time complexity. We also learned the C++ program for this problem and the complete approach by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages.

Updated on: 24-Nov-2021

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements