今天做PAT时见到的Mark下了:
long long gcd(long long a, long long b) {return b == 0 ? a : gcd(b, a % b);}
或者用迭代方式:
long long gcd(long long a,long long b) { long long z; while(b) { z=a%b; a=b; b=z; } return a; }
特地去查了一下求最大公约数的算法,结果如下:
辗转相除法
有两整数a和b:
① a%b得余数c
② 若c=0,则b即为两数的最大公约数
③ 若c≠0,则a=b,b=c,再回去执行
例如求27和15的最大公约数过程为:
27÷15 余12 15÷12余3 12÷3余0因此,3即为最大公约数
以及另一种:
相减法
有两整数a和b:
① 若a>b,则a=a-b
② 若a<b,则b=b-a
③ 若a=b,则a(或b)即为两数的最大公约数
④ 若a≠b,则再回去执行①
例如求27和15的最大公约数过程为:
27-15=12( 15>12 ) 15-12=3( 12>3 )
12-3=9( 9>3 ) 9-3=6( 6>3 )
6-3=3( 3==3 )
因此,3即为最大公约数
初中老师见了要吐血……