1440. Cycle of Powers

Medium3.5 points estimatedNumber TheoryMaths

A lighthouse keeper logs a signal using a repeating wheel with m positions. Starting at position 1, every tick multiplies the current position by a and wraps around modulo m. If the wheel ever returns to position 1, the keeper wants to know how many ticks that takes for the first time.

Given a and m, return the smallest k >= 1 such that a^k mod m == 1. If no such k exists (which happens exactly when gcd(a, m) != 1), return -1. Note that a may be larger than m; reduce it first. Aim for roughly O(sqrt(m) + log^2 m) time and O(1) extra space.

Example 1

Input:
a = 3, m = 7
Output:
6
Explanation:

The powers of 3 modulo 7 are 3, 2, 6, 4, 5, 1, so the first return to 1 happens at k = 6.

Example 2

Input:
a = 4, m = 15
Output:
2
Explanation:

4 squared is 16, which is 1 modulo 15, and 4 itself is not 1, so the order is 2.

Example 3

Input:
a = 6, m = 9
Output:
-1
Explanation:

gcd(6, 9) = 3, so no power of 6 can be 1 modulo 9 and the answer is -1.

Constraints

2 ≤ m ≤ 9*107

1 ≤ a ≤ 109

Products of two residues below m stay under 253, so plain 64-bit (or double) 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) + log^2 m)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…