Power with modulu

R

Roie Kerstein

Hello!

I want to compute a**b%c for very long numbers.
Computing a**b and then applying modulu is not practical, since it takes
ages.
There is a built-in optional parameter to the long.__pow__(a,b[,modulu]),
and it works well.
My question is: How can I write it is a form of an expression, like a**b?
I prefer not to fill my script with calls of the form long.__pow__(a,b,c).
 
M

Mitja

Hello!

I want to compute a**b%c for very long numbers.
Computing a**b and then applying modulu is not practical, since it takes
ages.
There is a built-in optional parameter to the long.__pow__(a,b[,modulu]),
and it works well.
My question is: How can I write it is a form of an expression, like a**b?
AFAIK you can't.
I prefer not to fill my script with calls of the form
long.__pow__(a,b,c).
That's a bit ugly, yes; pow is also a builtin, e.g.:
pow(21,443,2)==1
 
B

Bengt Richter

Hello!

I want to compute a**b%c for very long numbers.
Computing a**b and then applying modulu is not practical, since it takes
ages.
There is a built-in optional parameter to the long.__pow__(a,b[,modulu]),
and it works well.
My question is: How can I write it is a form of an expression, like a**b?
I prefer not to fill my script with calls of the form long.__pow__(a,b,c).
You could subclass long to use a fixed modulus stored as a class variable,
and make a factory function to return a class for a particular modulus, e.g.,
... class M(long):
... def __pow__(self, p):
... return type(self)(long.__pow__(self, p, self.modulus))
... def __repr__(self): return 'M(%s %%%s)'% (long.__repr__(self), self.modulus)
... M.modulus = modulus
... return M
... M(36028797018963968L %7)

note that print will use the __str__ method of the underlying long 2

I made the power operation return the same type M(4L %7)

But if you use another operation, the result will be converted to the dominant type,
since the only operation I overrode was __pow__. But you could override them all, by hand
or automate the wrapping with a metaclass.
40.0

You could also make M take an optional initialization parameter to override what's set with mmod.
Or if you override all the time, not bother with mmod. Depends on what you need & how you are
going to use the stuff.

Regards,
Bengt Richter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,213
Messages
2,571,105
Members
47,698
Latest member
TerraT521

Latest Threads

Top