简体   繁体   中英

Digit wise modulo for calculating power function for very very large positive integers

Hi I am writing a code to calculate P^Q where

P, Q are positive integers which can have number of digits upto 100000

I want the result as

result = (P^Q)modulo(10^9+7)

Example:

P = 34534985349875439875439875349875 
Q = 93475349759384754395743975349573495
Answer = 735851262

I tried using the trick:

 (P^Q)modulo(10^9+7) = (P*P*...(Q times))modulo(10^9+7)

 (P*P*...(Q times))modulo(10^9+7) = ((Pmodulo(10^9+7))*(Pmodulo(10^9+7))...(Q times))modulo(10^9+7)

Since both P and Q are very large, I should store them in an array and do modulo digit by digit.

Is there any efficient way of doing this or some number theory algorithm which I am missing?

Thanks in advance

Here is a rather efficient way:

1)Compute p1 = P modulo 10^9 + 7

2)Compute q1 = Q modulo 10^9 + 6

3)Then P^Q modulo 10^9 + 7 is equal to p1^q1 modulo 10^9 + 7. This equality is true because of Fermat's little theorem. Note that p1 and q1 are small enough to fit in 32-bit integer, so you can implement binary exponention with standard integer type(for intermidiate computations, 64-bit integer type is sufficient because initial values fit in 32-bits).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM