最大的共同分母计数器

时间:2013-10-05 22:16:26

标签: python greatest-common-divisor

我想在python中创建一个最大的公约数,但我不确定如何去做,或者从哪里开始......我所得到的几乎就是这个等式(a和b是编号):

a = b * quotient + remainder

我希望计数器打印所有步骤,直到余数低于a,然后显示GCD。

我还搜索了一些,发现2个数字的商可以用//命令和余数用%命令完成,基本上就是这样:

a = b * (a // b) + (a % b)

我也知道我需要一个循环的计数器,但我不知道如何去做...帮助将非常感激。

我见过GCD的一些代码,但找不到能显示所有步骤的代码。

1 个答案:

答案 0 :(得分:0)

def gcd_steps(a, b):
    steps = []
    # this is the standard GCD finding algorithm;
    # we simply amend it with "step tracking"
    while b:
        # a, b = b, a % b
        tmp = a
        a = b
        b = tmp % b
        steps.append(a)
    return steps  # normally we'd want to return `a`
                  # but you want the steps not just the result

steps = gcd_steps(125 * 123 * 12314, 25 * 149)

# print the list with `->` between the steps
print(" -> ".join(str(x) for x in steps))

(结果将是最后一步,您可以通过获取列表的最后一个元素来访问:steps[-1]

<强>输出:

3725 -> 900 -> 125 -> 25