1459. Hidden Exponent
A lock stores only the value b, obtained by repeatedly multiplying a secret starter by itself and reducing the result modulo the prime m. Given a, b and the prime m, find the smallest non-negative integer x such that a^x mod m == b; note that a^0 is 1. If no such exponent exists, return null. Checking every exponent is too slow when m is large, so split the search into baby steps stored in a hash table and giant steps of about sqrt(m) powers, making sure the smallest valid exponent is the one reported. Aim for O(sqrt(m)) time and O(sqrt(m)) space.
Example 1
- Input:
- a = 2, b = 3, m = 5
- Output:
- 3
- Explanation:
2^3 = 8 and 8 mod 5 is 3, and no smaller exponent gives 3.
Example 2
- Input:
- a = 4, b = 2, m = 5
- Output:
- null
- Explanation:
The powers of 4 modulo 5 only alternate between 1 and 4, so the value 2 is never reached.
Example 3
- Input:
- a = 7, b = 1, m = 11
- Output:
- 0
- Explanation:
The exponent 0 already gives 1, so the smallest exponent is 0.
Constraints
2 ≤ m ≤ 9 * 107 and m is prime
1 ≤ a, b < m
Products of two residues stay below 253, so plain 64-bit arithmetic is enough.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(sqrt(m))
- Space
- O(sqrt(m))