| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2727 人关注过本帖
标题:求解三元一次不定方程
只看楼主 加入收藏
medicihophy
Rank: 1
等 级:新手上路
威 望:1
帖 子:102
专家分:0
注 册:2007-7-28
收藏
得分:0 

#include<iostream.h>
int a,b,c,n;
int mertix[201][201];
int answer[3];
int check()
{

for(int i=0;i<201;i++)
for(int j=0;j<201;j++)
{
mertix[i][j]=a*i+b*j-n;
if(mertix[i][j]%c==0)
{
answer[0]=i;
answer[1]=j;
answer[2]=mertix[i][j]/c;

return 0;
}
}
return 1;

}
int main()
{
while(cin >> a >> b >> c >> n )
{
if(check())
{
cout<<-1<<endl;
}
else
{
cout << answer[0] <<" "<< answer[1] <<" "<< answer[2] <<endl;
}
}
return 0;
}


2007-07-29 17:32
medicihophy
Rank: 1
等 级:新手上路
威 望:1
帖 子:102
专家分:0
注 册:2007-7-28
收藏
得分:0 
这个是不是会超时什么的?

2007-07-29 17:33
daiwei89
Rank: 1
等 级:新手上路
帖 子:9
专家分:0
注 册:2007-7-27
收藏
得分:0 
一般都是先学C语言,这样再学其他的语言就轻松的多啦。
2007-07-29 18:45
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
收藏
得分:0 
回复:(leeco)求解三元一次不定方程

The Chinese remainder theorem is the key to solve

a_1 x_1 + a_2 x_2 + ... + a_r x_r = n

for integer solutions. You may want to be familiar with the theorem.

For the case r=2, i.e., a_1 x_1 + a_2 x_2 = n, the extended Euclid algorithm is your friend. I implemented it inside the code below.

For the case r=3, by using the extended Euclid algorithm twice, you arrive at the solution.

For the case r>3, you can still use the algorithm r-1 times to solve it. But it become so cubersome that you want to use the Chinese remainder theorem and its corresponding algorithm instead.

I am not using the theorem in the code.

=================================================

#include <iostream>
using namespace std;

int gcd(int a, int b, int& x, int& y)
{
int x2=1, y2=0, t, q, a2=a, b2=b;

x=0;
y=1;
while(b)
{
t = b;
q = a / b;
b = a% b;
a = t;

t = x;
x = x2-q*x;
x2 = t;

t = y;
y = y2-q*y;
y2 = t;
}

x=x2;
y=y2;


// make x>=0, y<=0
x=x+b2/a;
y=y-a2/a;

return a;
}

int main()
{
int a, b, c, x, y, z, n, v, w, x1, y1, x2, y2, t;

while(cin>>x>>y>>z>>n)
{
v=gcd(x, y, x1, y1);
w=gcd(v, z, x2, y2);

if(n%w)
cout<<-1<<endl;
else
{
t=n/w;

// calculate one solution: here a>=0, b<=0, c>=0
a=t*x2*x1;
b=t*x2*y1;
c=t*y2;

// adjust b and c to make b non-negative
c=-c;
t=-b/z+1;
b+=z*t;
c+=t*y;

cout<<a<<" "<<b<<" "<<c<<endl;
}
}

return 0;
}



I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-07-30 08:42
leeco
Rank: 4
等 级:贵宾
威 望:10
帖 子:1029
专家分:177
注 册:2007-5-10
收藏
得分:0 
回复:(HJin)回复:(leeco)求解三元一次不定方程
是的,我也是想用扩展欧几里德来解决这个问题,但是不断的Wrong Answer和Runtime Error,谢谢你的指点。让我仔细看一下代码
2007-07-30 22:44
快速回复:求解三元一次不定方程
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019608 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved