求方程5x+6y=M的正整数解中x和y都是整数的解,只有M和N都是正整数时,且x,y范围为[1,N].
#include <iostream>
using namespace std;
void main(){
int f(int M, int N);
cout << f(500, 650) << endl;
}
int f(int M, int N)
{
//5x+6y=M
int i, j, count = 0;
if(M <= 0 || N <= 0)
return -1;
for(i = 1; i <= N; ++i)
{
for(j = 1; j <= N; ++j)
{
if (5 * i + 6 * j == M)
{
cout<< i<<"\t"<< j<<endl;
++count;
}
}
}
return count;
}
f函数中,需要先判断M和N是否为正整数,有一个不是正整数,就返回-1。
运行结果及代码如下:
代码:
#include <iostream>
using namespace std;
int f(int M,int N);
void main()
{
cout << f(500,650)<<endl;
}
int f(int M,int N)
{
int x,y,count = 0;
if(M<=0 || N<=0)
return -1;
for (x=1;x<=N;x++)
{
for (y=1;y<=N;y++)
{
if(5*x+6*y==M)
{
cout << x <<" "<<y<<endl;
count++;
}
}
}
return count;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!