Solution
Let
Define
and let
At position , we need to choose an unused value p_i such that
Let
The congruence
has a solution if and only if
If this condition does not hold, there is no valid permutation.
Otherwise, define
After dividing the congruence by , we get
Also,
Therefore, \frac{P_{i-1}}{g} has a multiplicative inverse modulo .
Hence, p_i must satisfy exactly one residue condition
where
Thus, at every step we only need to find an unused number from one residue class modulo .
Why any representative works
Suppose
Since
and
we have
Because M\mid x-y, it follows that
Therefore,
So every number from the required residue class produces exactly the same next prefix product.
Now define
and
Since
we have
Therefore,
Thus, every future modulus divides the current modulus.
So if two values are equal modulo the current , they also remain equal modulo every future modulus.
Therefore, all unused representatives of the current residue class are completely equivalent, and we may choose any of them.
Maintaining unused values
Every possible value of is a divisor of .
For every divisor , group the numbers 1,2,\dots,n by their residue modulo .
For every residue class, keep a pointer to the first candidate that has not yet been checked.
When a residue class is requested, move its pointer while the current value has already been used.
If there is no unused value left in this class, then no valid continuation exists.
Otherwise, choose this value as p_i and mark it as used.
Finally, update
Correctness
At every step, the condition on p_i is equivalent to belonging to exactly one residue class modulo .
Every value from this class produces exactly the required next prefix product.
Since all future moduli divide the current modulus, all representatives of this residue class remain equivalent for all future positions.
Therefore, choosing any unused representative is always safe.
If no unused representative exists, then no unused value can satisfy the current congruence.
Hence, the algorithm constructs a valid permutation exactly when one exists.
Complexity
Let be the number of divisors of .
For every divisor, every value may be processed only a constant number of times.
Therefore, the total complexity is
time and
memory.