You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
523 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include<iostream>
using namespace std;
//暴力法
int gcd(int a,int b)
{
int ans=a>b? b:a;
while(ans>1&&(a%ans!=0||b%ans!=0))
{
ans--;
}
return ans;
}
//辗转相除法
//假设a>b,如果a不能被b整除则将b赋值给a余数赋值给b重复执行a%b,直到a能够被b整除。此时返回b的值则为最大公约数。
int gcd2(int a,int b)
{ int c;
if(a<b)
{ a=a+b;
b=a-b;
a=a-b;
}
c=a%b;
while(a%b!=0)
{ a=b;
b=c;
c=a%b;
}
return b;
}
int main() {
int a,b;
cin>>a>>b;
cout<<gcd(a,b)<<endl;
cout<<gcd2(a,b)<<endl;
return 0;
}