![]() |
VOOZH | about |
Given three integers a, b and m. Find an integer k such that where a and m are relatively prime. If it is not possible for any k to satisfy this relation, print -1.
Examples:
Input: 2 3 5
Output: 3
Explanation:
a = 2, b = 3, m = 5
The value which satisfies the above equation
is 3, because
=> 23 = 2 * 2 * 2 = 8
=> 23 (mod 5) = 8 (mod 5)
=> 3
which is equal to b i.e., 3.
Input: 3 7 11
Output: -1
A Naive approach is to run a loop from 0 to m to cover all possible values of k and check for which value of k, the above relation satisfies. If all the values of k exhausted, print -1. Time complexity of this approach is O(m)
An efficient approach is to use baby-step, giant-step algorithm by using meet in the middle trick.
Baby-step giant-step algorithm
Given a cyclic group G of order 'm', a generator 'a' of the group, and a group element 'b', the problem is to find an integer 'k' such that
So what we are going to do(according to Meet in the middle trick) is to split the problem in two parts of each and solve them individually and then find the collision.
Now according to the baby-step giant-step
algorithm, we can write 'k' as
with and and .Therefore, we have:Therefore in order to solve, we precompute for different values of 'i'. Then fix 'b' and tries values of 'j' In RHS of the congruence relation above. It tests to see if congruence is satisfied for any value of 'j', using precomputed values of LHS.
Let's see how to use above algorithm for our question:-
First of all we have to write , where Obviously, any value of k in the interval [0, m) can be represented in this form, where and
Replace the 'k' in above equality, we get:-
Output:
3
-1
Time complexity: O(sqrt(m)*log(b))
Auxiliary space: O(sqrt(m))
A possible improvement is to get rid of binary exponentiation or log(b) factor in the second phase of the algorithm. This can be done by keeping a variable that multiplies by 'a' each time as 'an'. Let's see the program to understand more.
Output:
3
-1
Time complexity: O(sqrt(m))
Auxiliary space: O(sqrt(m))
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.