有效地计算Knuth的向上箭头符号模数

时间:2015-07-16 03:29:01

标签: optimization recursion modulus exponentiation

我已经将memoization用作字典了。还有什么我可以做的吗?我怀疑for循环可能会被优化。作为参考,我正在计算knuth_arrow(2, 3, 9, 14**8)

memo = {}

def knuth_arrow(a, n, b, m):
    if (a, n, b) in memo:
        return memo[(a, n, b)]

    if n == 0:
        return (a*b) % m

    if n == 1:
        s = pow(a, b, m)
        memo[(a, n, b)] = s
        return s

    if n > 1:
        s = a
        for i in range(b-1):
            s = knuth_arrow(a, n-1, s, m)

        memo[(a, n, b)] = s
        return s

0 个答案:

没有答案