Last M digits of expression A^N

Gerald Britton gerald.britton at gmail.com
Fri Feb 5 15:21:13 EST 2010


On Fri, Feb 5, 2010 at 3:14 PM, mukesh tiwari
<mukeshtiwari.iiitm at gmail.com> wrote:
> Hello everyone. I am kind of new to python so pardon me if i sound
> stupid.
> I have to find out the last M digits of expression.One thing i can do
> is (A**N)%M but my  A and N are too large (10^100) and M is less than
> 10^5. The other approach   was  repeated squaring and taking mod of
> expression. Is there any other way to do this in python more faster
> than log N.
>
> def power(A,N,M):
>    ret=1
>    while(N):
>        if(N%2!=0):ret=(ret*A)%M
>        A=(A*A)%M
>        N=N//2
>    return ret
> --
> http://mail.python.org/mailman/listinfo/python-list
>

http://docs.python.org/3.1/library/decimal.html#decimal.Context.power

-- 
Gerald Britton



More information about the Python-list mailing list