Files
python/C++课程/第十二课二进制进阶与多重循环/最大公约数.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

40 lines
562 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}