GCD的迭代计数器

时间:2016-10-19 18:47:12

标签: python iteration

我有以下代码用于计算两个数字的GCD:

def gcd(m, n):
   r = m % n
   while r != 0:
      m = n
      n = r
      r = m % n
   return n

print ("\n", "gcd (10, 35) = ", gcd(10, 35))

print ("\n", "gcd (735, 175) = ", gcd(735, 175))

print ("\n", "gcd (735, 350) = ", gcd(735, 350))

我想计算算法在找到GCD之前必须经历的迭代次数。我在制作for循环时无法确定迭代次数。

1 个答案:

答案 0 :(得分:3)

def gcd(m, n):
   r = m % n
   counter = 0
   while r != 0:
      m = n
      n = r
      r = m % n
      counter += 1
   return n, counter