1.辗转相除法:
//获取最大公约数 int getGCD(int a,int b){ int temp; if(a < b){ temp = a; a = b; b = temp; } if(a%b == 0){ return b; }else{ return getGCD(b,a%b); }
设两数为a、b(a≥b),求a和b最大公约数
的步骤如下:
![](https://gss1.bdstatic.com/-vo3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D32/sign=ac46d82c2d7f9e2f74351b0a1d30b3f4/caef76094b36acaf2310fc3676d98d1000e99c03.jpg)
(1)用a除以b(a≥b),得
。
![](https://gss2.bdstatic.com/-fo3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D137/sign=0d91b43ebd4543a9f11bfecf29168a7b/0bd162d9f2d3572caf57f6168013632763d0c347.jpg)
(2)若
,则
;
![](https://gss3.bdstatic.com/7Po3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D41/sign=79d6426f007b020808c93ee060d988fa/203fb80e7bec54e7210170d4b3389b504ec26a0e.jpg)
![](https://gss2.bdstatic.com/-fo3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D59/sign=13150e208bcb39dbc5c0675fd2167081/3c6d55fbb2fb4316a3f310b02aa4462308f7d308.jpg)
(3)若
,则再用b除以
,得
.
![](https://gss1.bdstatic.com/9vo3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D43/sign=50366621bcfd5266a32b3d17a9184eab/42166d224f4a20a497de560d9a529822730ed03c.jpg)
![](https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D12/sign=07386c2d9b2397ddd2799c065882dfa9/c9fcc3cec3fdfc03f045b672de3f8794a4c2263e.jpg)
![](https://gss1.bdstatic.com/9vo3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D143/sign=708e2a6afc03738dda4a0826801ab073/09fa513d269759eef4e23501b8fb43166c22df4e.jpg)
(4)若
,则
;若
,则继续用
除以
,......,如此下去,直到能整除为止。
![](https://gss1.bdstatic.com/-vo3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D41/sign=78b1ceabf9deb48fff69a0dff11f3877/d01373f082025aaf21442a01f1edab64024f1a81.jpg)
![](https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D63/sign=08a2351d3cd12f2eca05ad634ec2287a/b7fd5266d0160924d856f6d1de0735fae7cd348c.jpg)
![](https://gss3.bdstatic.com/7Po3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D43/sign=13efecea0be9390152028c3d7aec2e62/dcc451da81cb39dbd9cb339cda160924aa1830f4.jpg)
![](https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D12/sign=03809ce54b34970a4373142d94ca157e/8601a18b87d6277f357c66f222381f30e824fc8a.jpg)
![](https://gss0.bdstatic.com/-4o3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D13/sign=7207680d9a52982201333dc0d6caec4c/35a85edf8db1cb137d7068d9d754564e93584bda.jpg)
其最后一个余数为0的除数即为
的最大公约数。
![](https://gss0.bdstatic.com/-4o3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D32/sign=cf3ad184c08065387feaa21196ddc250/bba1cd11728b4710e53ba906c9cec3fdfd0323e7.jpg)
//减法求最大公约数
#include<stdio.h> int main() { int a,b; scanf("%d%d",&a,&b); while(a!=b) { if(a>b) a-=b; else b-=a; } printf("%d",a); }