同余定理(欧几里得算法)

如果  (a-b)%m==0  那么 a%m==0  b%m==0

a,b关于模m同余。

求最大公约数

#include "pch.h"
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
int gcd(int a, int b)
{
    while (a != b)
    {
        if (a > b)    a = a-b;
        else  b = b - a;
    }
    return a;
}
int main()
{
    int x, y;
    cin >> x >> y;
    cout << gcd(x, y) << endl;
    return 0;
}
更相减损法
 
#include "pch.h"
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
int gcd(int a, int b)
{
    if (b == 0)    return a;
    else return gcd(b, a%b);
}
int main()
{
    int x, y;
    cin >> x >> y;
    cout << gcd(x, y) << endl;
    return 0;
}
欧几里得算法

gcd(a,b)=gcd(b,a mod b);

设d是a,b的最大公约数,a=kd,b=ld;  

所以d也是a,b,r,的公约数。  把两个大的数转化为两个小的数。

拓展欧几里得算法 (挖坑回来写)

No matter how you feel, get up , dress up , show up ,and never give up.
原文地址:https://www.cnblogs.com/Kaike/p/9821955.html