oppressionslayer
oppressionslayer

Reputation: 7224

Trouble converting a modulus pow() function from Lua to Python

I have tried to rewrite a Lua mod_pow() function ( which works ) to Python. The syntax and everything looks ok to me so I'm not sure what I'm missing. Does anyone know what I need to change in my Python code to get it to work and give 81 as the answer as the Lua code does?

Lua working code:

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 non working code:

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

Upvotes: 2

Views: 136

Answers (1)

namannimmo
namannimmo

Reputation: 156

^ is bitwise XOR in python. reference: here

Upvotes: 1

Related Questions