Dexter plays with GP

2.3

3 votes
Multiplicative Inverse, Mathematics, Open, Easy-Medium, Number Theory
Problem

Today, Dexter Morgan has Code Monk on his death table. He will ask T questions from Code Monk. If the monk can answer all these questions, he will let him go, otherwise Dexter will kill the monk. Each question is of the following form:

You form a geometric progression with N numbers. The first term of the progression is 1. r is the common ratio of the progression. p is a prime number. All the multiplication operations are defined under the modulo p, i.e., ai(ai1r) (mod p), for i>1 and a1=1. Now, the sum of the first N terms of the GP modulo p, is S. Now, Dexter only tells the values of r,p and S to the monk, and asks if he can find the value of N such that a1+a2+...+aNS (mod p) and 1N<p.

Note : Dexter also tells a special property about r to the monk that if we form a set of the numbers r,r2,r3,...,rp1 (mod p), then that set will contain all the numbers from 1 to p1.

Input
The first line of input contains a single integer T, denoting the number of questions Dexter asks from Code Monk. The next T lines contain three space-separated integers r,S and p, denoting the common ratio, the prime number and the sum of the first N terms of the GP (mod p), respectively.

Output
For each question, you have to print only one integer, the value of N which satisfies the condition given in the problem. If it is not possible to get S as the sum of the GP (mod p) for any N, print 1.

Constraints
1T100.
2p<109 and p is prime.
1r<p
1S<p

Time Limit: 5
Memory Limit: 256
Source Limit:
Explanation

Case 1:
r=5,S=2,p=7
a1=1,a2=5,a3=4,a4=6.
We can see that a1+a2+a3+a42 (mod 7). So, answer for this case is N=4.

Case 2:
r=5,S=5,p=7
We can see that there is no 1N<p, that gives S=5 for the sum og the GP.
So, we have the answer 1.

Editor Image

?