辗转相除法
#include<bits/stdc++.h>
using namespace std;
int gcd(int a,int b){
int c;
if(a%b==0)return b;
if(b%a==0)return a;
if(a>b){
c=a%b;
while(c!=0){//余数和除数反复相除直至余数为0
a=b;
b=c;
c=a%b;
}
}
else{
c=b%a;
while(c!=0){
a=a;
b=c;
c=a%b;
}
}
return b;
}
int main(){
int x,y;
cin>>x>>y;
cout<<gcd(x,y);
}
递归简化
int gcd(int a,int b)
{
if(a<b) //保证a大于b
{
swap(a,b);
}
if(a%b == 0)
{
return b;
}
return gcd(b,a%b);
}
辗转相减法
#include <iostream>
using namespace std;
int gcd(int m,int n)
{
while (m != n)
{
if (m > n)
{
m = m - n;
}
else
{
n = n - m;
}
}
return m;
}