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

青春壹個敷衍的年華 提交于 2020-01-03 06:20:06

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/25117346/digit-wise-modulo-for-calculating-power-function-for-very-very-large-positive-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!