Home > Article > Backend Development > Using C++ programming, find the number of solutions to the equation x + y + z <= n
In this article, we will explain the method on how to find the solution of the equation x y z<=n. In this problem, we have an equation with four variables and the task is to find the solution of 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 loop through all (x, y), (y,z) by isolating each variable and checking if it satisfies the equation , the value of (x,z).
Now we will use brute force method to find the solution to the given problem.
In this program, we will traverse all possible values of (x,y), (y,z) and (x,z) to satisfy the equation z
#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"; }
17
In this program, we will use a nested for loop to traverse all (x ,y), (y, z) and (x, z), and check whether the equation satisfies the condition, and if so, add the answer.
In this article, we solved a problem to find the number of solutions that satisfy the equation x y z<= n, with a time complexity of O(X*Y). We also learned a C program to solve this problem and the complete solution. We can write the same program in other languages like C, Java, Python and others.
The above is the detailed content of Using C++ programming, find the number of solutions to the equation x + y + z <= n. For more information, please follow other related articles on the PHP Chinese website!