将模数pow()函数从Lua转换为Python时出现问题

2024-05-18 21:01:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我曾尝试将Lua mod \u pow()函数(可以工作)重写为Python。语法和一切看起来都好,所以我不知道我错过了什么。有没有人知道我需要在Python代码中修改什么才能让它工作,并像Lua代码那样给出81作为答案?你知道吗

Lua工作代码:

function modPow(b,e,m)
        if m == 1 then
                return 0
        else
                local r = 1
                b = b % m
                while e > 0 do
                        if e % 2 == 1 then
                                r = (r*b) % m
                        end
                        e = e >> 1     --use 'e = math.floor(e / 2)' on Lua 5.2 or older
                        b = (b^2) % m
                end
                return r
        end
end

modPow(7,4,145)
81.0

Python非工作代码:

def modular_pow(b, e, m):
    if m == 1: 
       return 0
    else:
      r=1
      b = b % m
      while e > 0:
        if e % 2 == 1:
           r = (r*b) % m
        e = e >> 1
        b = (b^2)% m
    return r

modular_pow(7,4,145)
7

Tags: 函数答案代码modreturnif语法else

热门问题