Fast modular computing in Python and Ruby

I was given the following algorithm that computes s, where s = g ^ u mod p in Python:

def modexp ( g, u, p ):
   """computes s = (g ^ u) mod p
      args are base, exponent, modulus
      (see Bruce Schneier book, _Applied Cryptography_ p. 244)"""
   s = 1
   while u != 0:
      if u & 1:
         s = (s * g)%p
      u >>= 1
      g = (g * g)%p;
   return s

However, when I convert the code to Ruby like this:

def modexp ( g, u, p )
    s = 1
    while u != 0
        if u & 1
            s = (s * g)%p
        end
        u >>= 1
        g = (g * g)%p
    end
    return s
end

I get different results. For instance:

Python 2.7 (r27:82500, Oct  6 2010, 12:29:13) 
[GCC 4.5.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import modexp
>>> modexp.modexp(96,25,17)
6

What is the correct answer from Python code compared to

>> require './modexp.rb'
=> true
>> modexp(96,25,17)
=> 14

Can anyone explain this? From what I read, Python and Ruby have the same syntax for bit-shifting and bitwise and are used in the code, so I don't think so. Does anyone have any other ideas?

+5
source share
2 answers

This is because bitwise & returns a number, and 0 is falsey in Python, but true in Ruby.

def modexp ( g, u, p )
    s = 1
    while u != 0
        puts "g: #{g}, s: #{s}, u: #{u.to_s(2)}"
        if u & 1
            s = (s * g)%p
        end
        u >>= 1
        g = (g * g)%p
    end
    return s
end

irb(main):032:0> modexp(96,25,17)
g: 96, s: 1, u: 11001
g: 2, s: 11, u: 1100
g: 4, s: 5, u: 110
g: 16, s: 3, u: 11
g: 1, s: 14, u: 1
=> 14

, s , u . , 1100 = 12, , 12 & 1 == 0. , Python if u & 1: ; Ruby, 0 , if u & 1 .

if u & 1 != 0.

+6

0 Ruby. if u&1 if (u&1) != 0.

+3

All Articles