0

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

gmfreak
  • 399
  • 4
  • 12
  • You might be interested in [The GNU Multiple Precision Arithmetic Library](http://gmplib.org/)? – Some programmer dude Aug 04 '14 at 11:15
  • If you decide to store on array, you can use BCD encoding for memory save. – Erdinç Taşkın Aug 04 '14 at 11:20
  • @JoachimPileborg Thanks. It looks interesting but as the number (10^9) is a prime number and this problem involves a prime modulus, I have a gut feeling that there is some number theory theorem which I forgot might help here. I am searching for some number theory trick as this question is more about math trick and less about programming paradigm. – gmfreak Aug 04 '14 at 11:21
  • Then maybe you should as on http://math.stackexchange.com/ instead? – Some programmer dude Aug 04 '14 at 11:33
  • @JoachimPileborg Thanks for pointing out. I was not aware of this. I have posted this question there. – gmfreak Aug 04 '14 at 11:39

1 Answers1

3

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).

kraskevich
  • 18,368
  • 4
  • 33
  • 45