C++中求解给定方程的正整数解
假设我们有一个函数f,它接受两个参数(x, y)。我们必须返回所有x和y对,对于这些对,f(x, y) = z。z作为输入给出,x,y是正整数。该函数是一个不断增长的函数。因此f(x, y) < f(x + 1, y)且f(x, y) < f(x, y + 1)。
为了解决这个问题,我们将采用直接的方法。取i的范围为1到1000,j的范围为1到1000,对于i,j的所有组合,如果f(i, j) = 0,则返回true,否则返回false。
考虑函数id(应该提供)对于加法为1,对于乘法为2。它也接受z值。
示例
让我们看看下面的实现,以便更好地理解:
#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));
}输入
1 7
输出
[[1, 6, ],[2, 5, ],[3, 4, ],[4, 3, ],[5, 2, ],[6, 1, ],]
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP