#P4454. [CQOI2018] 破解D-H协议

    ID: 3386 远端评测题 1000ms 500MiB 尝试: 0 已通过: 0 难度: 7 上传者: 标签>2018重庆各省省选枚举,暴力素数判断,质数,筛法逆元

[CQOI2018] 破解D-H协议

Description

Assume the two parties are named Alice and Bob. The protocol works as follows (where mod\bmod denotes the modulo operation):

  1. The protocol specifies a fixed prime PP and a primitive root modulo PP, gg. The values P\boldsymbol P and g\boldsymbol g are public and do not need to be kept secret.

  2. Alice generates a random number aa, computes A=gamodPA=g^a \bmod P, and sends AA to Bob over the insecure channel.

  3. Bob generates a random number bb, computes B=gbmodPB=g^b \bmod P, and sends BB to Alice over the insecure channel.

  4. Bob computes the key K=AbmodPK=A^b \bmod P from the received AA, and Alice computes K=BamodPK=B^a \bmod P from the received BB.

  5. Both parties obtain the same KK, namely gabmodPg^{ab} \bmod P. KK is the encryption key for later communication.

In this process, only AA and BB can be eavesdropped, while aa, bb, and KK remain secret. Given the four numbers AA, BB, PP, and gg, it is not easy to compute KK, so KK can serve as a secure key.

Of course, security is relative. The security of the protocol depends on the sizes of the values. Typically, aa, bb, and PP are chosen as large integers with hundreds of bits to prevent compromise. However, if Alice and Bob are lazy in programming and, to avoid implementing big-integer arithmetic, choose values less than 2312^{31}, then cracking their key becomes relatively easy.

Given nn pairs of eavesdropped AA and BB, you need to try to crack the key KK.

Input Format

The first line contains two space-separated positive integers gg and PP.

The second line contains a positive integer nn, indicating that Alice and Bob performed nn sessions (i.e., ran the protocol nn times).

Then follow nn lines. Each line contains two space-separated positive integers AA and BB, representing the eavesdropped values AA and BB for one session.

Output Format

Output nn lines. Each line contains a single positive integer KK, which is the key you cracked for that session.

3 31
3
27 16
21 3
9 26
4
21
25

Hint

For 30%30\% of the testdata, 2A,B,P10002\le A,B,P\le 1000.

For 100%100\% of the testdata, 2A,B<P<2312\le A,B<P<2^{31}, 2g<202\le g<20, 1n201\le n\le 20.

Statement fixed by @Starrykiller.

Translated by ChatGPT 5