简体   繁体   English

Euclid算法的python代码中的奇怪错误

[英]Strange bug in python code of Euclid's algorithm

I'm trying to write a simple python code that computes the greatest common divisor of two integers. 我正在尝试编写一个简单的python代码,该代码计算两个整数的最大公约数。

def gcd(a,b):
  if (b==0):
    return a
  gcd(b,a%b)

This simple code uses the Euclid's algorithm . 这个简单的代码使用Euclid算法。 The problem is that it doesn't return except when b is zero . 问题在于,除非b为零,否则它不会返回。 what is the source of this bug ? 该错误的根源是什么?

Add return in recursive call as well. 以及在递归调用中添加return。

def gcd(a,b):
  if (b==0):
    return a
  return gcd(b,a%b)

You should return function call: 您应该返回函数调用:

def gcd(a,b):
  if (b==0):
    return a
  return gcd(b,a%b)

Your code doesn't return the return value of the recursive call. 您的代码不返回递归调用的返回值。

def gcd(a,b):
  if (b==0):
    return a
  return gcd(b,a%b)

This should work. 这应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM