使用Python 3和Euclid的算法计算列表的gcd

时间:2018-02-16 14:47:33

标签: python greatest-common-divisor

我正在尝试使用Euclid的算法来使用Python 3计算列表的gcd。但是,我得到错误" TypeError:%支持的操作数类型:' NoneType'和' int'"。我到处检查,但仍无法找到我的代码有什么问题。 这是我的代码,

# To get the gcd of a list
def gcd(numbers):
    m = numbers[0]
    for i in range(1, len(numbers)):
        m = gcd2(m, numbers[i])
    return m

# Use Euclid’s algorithm to calculate the gcd of two numbers
def gcd2(m, n):
    if m % n != 0:
        gcd2(n, m % n)
    else:
        return n

def main():
    str = [44, 6, 12, 24, 4, 18]
    print(gcd(str))

main()

2 个答案:

答案 0 :(得分:2)

您错过了gcd2第3行的退货声明。更新后的功能如下。

$rootScope.$on('$locationChangeStart', function (event, next, current) {
    // redirect to login page if not logged in
    if ($location.path() !== '/login' && !$rootScope.globals.currentUser) {
        $location.path('/login');
    }

    // redirect to home page if logged in
    if ($location.path() === '/login' && $rootScope.globals.currentUser) {
        $location.path('/home');
    }
});

希望这有帮助。

答案 1 :(得分:0)

def gcd2(m, n):
    if m % n != 0:
        gcd2(n, m % n)
    else:
        return n

if您没有返回任何内容,因此默认为None。在那里添加回报。