Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

果然还是传说中的扩展欧几里得算法好使

Posted by richardzzz at 2009-04-24 21:38:05 on Problem 1061
int exGcd(int a, int b, int &x0, int &y0)
{
  if(b == 0)
  {
     x0 = 1;
     y0 = 0;
     return a;
  }
  int r = exGcd(b, a % b, x0, y0);
  int t = x0;
  x0 = y0;
  y0 = t - a / b * y0;
  return r;
}
就这个,它返回gcd(a,b)
对于ax+by=c
如果c%gcd(a,b)!=0无解整数解
否则,通解为(t为任意整数):
x = x0*c/gcd(a,b) + b/gcd(a, b) * t
y = y0*c/gcd(a,b) - a/gcd(a, b) * t 
然后根据原题计算出x或y的最小正整数,x0或y0可能是负数(因为a,b可以用负数),所以计算的结果要稍微处理一下
另c语言可以用__int64

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator