求最大公约数

来源:互联网 发布:js ajax 实例 编辑:程序博客网 时间:2024/06/14 16:45

python

法一:(求差运算)

法二: 定义法: 最大公约数: 同时被整除的最大正整数(求模运算)

"""goal: claculate the gcdauthor: Cindydatatime: 2017/ 12/ 11"""def get_gcd_one_way(num_1, num_2):    while num_2 != 0:        if num_1 < num_2:            temp = num_1            num_1 = num_2            num_2 = temp        t = num_1 - num_2        num_1 = num_2        num_2 = t    return num_1def get_gcd_another_way(a, b):    index = min(a, b)    gcd = 1    for i in range(2, index+1):        if a % i == 0 and b % i == 0:            gcd = i        else:            continue    return gcdif __name__ == '__main__':    m = input('please input a number: ')    n = input('please input another number: ')    print('The one way gcd is: ', get_gcd_one_way(eval(m), eval(n)))    print('The another way gcd is', get_gcd_another_way(eval(m), eval(n)))

运行结果:

please input a number: 16please input another number: 48The one way gcd is:  16The another way gcd is 16



原创粉丝点击