Find Positive Integer Solution for a Given Equation in C++

C++Server Side ProgrammingProgramming

Suppose we have a function f that takes two parameters (x, y). We have to return all pairs of x and y, for which f(x, y) = z. The z is given as input, and x, y are positive integers. The function is constantly increasing function. So f(x, y) < f(x + 1, y) and f(x, y) < f(x, y + 1).

To solve this we will perform straight-forward approach. Take i in range 1 to 1000, and j in range 1 to 1000, for all combinations of i,j, if f(i, j) = 0, then return true, otherwise false.

Consider the function id (should be provided) is 1 for Addition, 2 for multiplication. It also takes the z value.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<int> > v){
   cout << "[";
      for(int i = 0; i<v.size(); i++){
         cout << "[";
            for(int j = 0; j <v[i].size(); j++){
               cout << v[i][j] << ", ";
            }
            cout << "],";
      }
      cout << "]"<<endl;
}
class CustomFunction {
   int id;
   public:
   CustomFunction(int id){
      this->id = id;
   }
   int f(int x, int y){
      if(id == 1)
         return y + x;
      else if(id == 2)
         return y * x;
      return 0;
   }
};
class Solution {
   public:
   vector<vector<int>> findSolution(CustomFunction& c, int z) {
      vector  < vector <int > > ans;
      for(int i = 1; i <= 1000; i++ ){
         for(int j = 1; j <= 1000; j++){
            if(c.f(i,j) == z){
               vector <int> t;
               t.push_back(i);
               t.push_back(j);
               ans.push_back(t);
            }
         }
      }
      return ans;
   }
};
main(){
   Solution ob;
   CustomFunction c(1);
   print_vector(ob.findSolution(c, 7));
}

Input

1
7

Output

[[1, 6, ],[2, 5, ],[3, 4, ],[4, 3, ],[5, 2, ],[6, 1, ],]
raja
Published on 20-Jan-2020 11:03:21
Advertisements