Блог пользователя thopecoder

Автор thopecoder, история, 6 лет назад, По-английски

Given three integers p,q,r. You have calculate remainder when $$$p^{(q!)}$$$ is divided by r. where '!' is factorial.

basically $$$p^{(q!)}$$$%r

constraints: 1 <= p,q,r <= 10^5

I have tried using naive factorization with binary exponentiation. Is there a more optimized approach for this problem?

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

»
6 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится +8 Проголосовать: не нравится

Edit: I'm sorry, but I noticed that my approach is wrong.

»
6 лет назад, скрыть # |
← Rev. 3  
Проголосовать: нравится +25 Проголосовать: не нравится

By an extension of Euler's theorem, $$$p^q\equiv p^{q\bmod\varphi(r)+\varphi(r)}\pmod r$$$.

Then, factorize $$$r$$$ to calculate $$$\varphi(r)$$$, in $$$O(\sqrt r)$$$.

Since $$$q!\bmod\varphi(r)$$$ can be calculated in $$$O(\sqrt q\log q)$$$, the total complexity is $$$O(\sqrt q\log q + \sqrt r)$$$.

»
6 лет назад, скрыть # |
 
Проголосовать: нравится +46 Проголосовать: не нравится

A simple loop would do the job:

for(int i=1; i<=q; i++)
	p = powM(p, i, r);