简体   繁体   English

用于计算非常大的正整数的幂函数的数位求模

[英]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,其中

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. 由于P和Q都很大,因此我应该将它们存储在数组中并逐位进行模运算。

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 1)计算p1 = P取10 ^ 9 + 7

2)Compute q1 = Q modulo 10^9 + 6 2)计算q1 = Q取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. 3)那么P ^ Q模10 ^ 9 + 7等于p1 ^ q1模10 ^ 9 +7。由于费马特的小定理,这种相等性成立。 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). 请注意,p1和q1足够小以适合32位整数,因此您可以使用标准整数类型实现二进制指数(对于中间计算,因为初始值适合32位,因此64位整数类型就足够了)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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