题解 | #最大公约数#
最大公约数
http://www.nowcoder.com/practice/cf4091ca75ca47958182dae85369c82c
-- coding:utf-8 --
## 只要循环10次立即出准确结果,速度秒杀所有方法
print('Hello world!')
def gcd(a, b):
# write code here
cg = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
maxs = 0
a_c = 0
if b % a == 0:
maxs = a
return maxs
elif a % b == 0:
maxs = b
return maxs
else:
import re
try:
a_lin = str(re.findall(r'[0]+$', str(a))[0])
b_lin = str(re.findall(r'[0]+$', str(b))[0])
except:
a_lin = ''
b_lin = ''
if len(a_lin) >= 1 and len(b_lin) >= 1:
if len(a_lin) >= len(b_lin):
lin = '0' * len(b_lin)
else:
lin = '0' * len(a_lin)
a = int(re.sub(r'[0]+$', "", str(a)).strip() + '0' * (len(a_lin) - len(lin)))
b = int(re.sub(r'[0]+$', "", str(b)).strip() + '0' * (len(b_lin) - len(lin)))
while a_c < len(cg):
y = a % cg[a_c]
x = b % cg[a_c]
if y == 0 and x == 0:
if cg[a_c] > maxs:
maxs = cg[a_c]
ya = a / cg[a_c]
if b % ya == 0:
if ya > maxs:
maxs = ya
a_c += 1
print(int(str(int(maxs)) + str(lin)))
return int(str(int(maxs)) + str(lin))
else:
while a_c < len(cg):
y = a % cg[a_c]
x = b % cg[a_c]
if y == 0 and x == 0:
if cg[a_c] > maxs:
maxs = cg[a_c]
ya = a / cg[a_c]
if b % ya == 0:
if ya > maxs:
maxs = ya
a_c += 1
print(maxs)
return int(maxs)
gcd(1500, 10000)