欧几里得算法又称辗转相除法,用于计算两个整数a和b的最大公约数
定理:gcd(a,b)= gcd(b,a mod b)
证明:
a可以表示成a= kb + r,则r = a mod b
1.假设d是a,b的一个公约数,则有 a|d,b|d,而r= a - kb,因此r|d
因此d是(b,a mod b)的公约数,证明充分性
2.假设d是(b,a mod b)的公约数,则b|d, r|d,但是a = kb +r
因此d也是(a,b)的公约数,证明必要性
因此(a,b)和(b,amod b)的公约数是一样的,其最大公约数也必然相等。
当b=0时,(a,0)的最大公约数是a
代码如下:
int gcd(int a, int b) { if(b == 0) return a; return gcd(b, a % b); }
拓展欧几里得算法用于在已知a,b求解一组x,y使得a*x+b*y=God(a,b)(解一定存在,根据数论中的相关定理)。拓展欧几里得常用在模线性方程及方程组中
实现代码:
int exgcd(int a, int b, int &x, int &y){ if(b == 0){ x = 1; y = 0; return a; } int r = exgcd(b, a % b, x, y); int t = x; x = y; y = t - a / b * y; return r; }
a'= b, b' = a % b 而言,我们求得 x, y使得 a'x+ b'y = gcd(a',b')
由于b'= a % b = a - a / b * b(这里的/是程序设计语言中的除法)
那么可以得到:
a'x+ b'y = gcd(a',b')===>
bx+ (a - a / b * b)y = gcd(a',b') = gcd(a,b)===>
ay+b(x - a / b*y) = gcd(a,b)
因此对于a和b而言,他们的相对应的p,q分别是y和(x-a/b*y).
我们来看几道例题:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 122308 | Accepted: 25943 |
Description
我们把这两只青蛙分别叫做青蛙A和青蛙B,并且规定纬度线上东经0度处为原点,由东往西为正方向,单位长度1米,这样我们就得到了一条首尾相接的数轴。设青蛙A的出发点坐标是x,青蛙B的出发点坐标是y。青蛙A一次能跳m米,青蛙B一次能跳n米,两只青蛙跳一次所花费的时间相同。纬度线总长L米。现在要你求出它们跳了几次以后才会碰面。
Input
Output
Sample Input
1 2 3 4 5
Sample Output
4
Source
代码实现如下:
#include <iostream> #include <iomanip> #include <stdio.h> #include <stdlib.h> #include <algorithm> #define ll long long int using namespace std; long long exgcd(ll a,ll b,ll &x,ll &y) { if(b==0) { x=1; y=0; return a; } ll r=exgcd(b,a%b,y,x); y-=x*(a/b); return r; } int main() { ll x,y,m,n,L; ll a,b,c,gcd; while(scanf("%lld%lld%lld%lld%lld",&x,&y,&m,&n,&L)!=EOF) { a=m-n; b=L; c=y-x; if(a<0) { a=-a; c=-c; } gcd=exgcd(a,b,x,y); if(c%gcd!=0) printf("Impossible"); else { x=x*c/gcd; int t=b/gcd; if(x>=0) x=x%t; else x=x%t+t; printf("%lld\n",x); } } return 0; }
二, hdu-2669
Romantic
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 8416 Accepted Submission(s): 3581
The Birds is Fly in the Sky.
The Wind is Wonderful.
Blew Throw the Trees
Trees are Shaking, Leaves are Falling.
Lovers Walk passing, and so are You.
................................Write in English class by yifenfei
Girls are clever and bright. In HDU every girl like math. Every girl like to solve math problem!
Now tell you two nonnegative integer a and b. Find the nonnegative integer X and integer Y to satisfy X*a + Y*b = 1. If no such answer print "sorry" instead.
Each case two nonnegative integer a,b (0<a, b<=2^31)
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<iomanip> #define ll long long int using namespace std; long long exgcd(ll a,ll b,ll &x,ll &y) { if(b==0) { x=1; y=0; return a; } ll re=exgcd(b,a%b,y,x); y=y-x*(a/b); return re; } int main() { ll a,b,x,y; while(cin>>a>>b) { ll gcd=exgcd(a,b,x,y); if(gcd!=1) { cout<<"sorry"<<endl; } else { while(x<0) { x=x+b; y=y-a; } cout<<x<<" "<<y<<endl; } } return 0; }