Odd or even permutation?

Apr 24, 2023ยท
Kam Chuen (Alex) Tung
Kam Chuen (Alex) Tung
ยท 1 min read

Problem Statement

Given NN and KK, generate the sequence ai:=Kโ‹…iโ€‰โ€‰โ€‰(modโ€‰โ€‰N)a_i := K \cdot i \,\,\, (\mathrm{mod }\,\, N). Let MM be the number of inversions1 of the sequence (a0,a1,โ€ฆ,ajโˆ’1)(a_0, a_1, \dots, a_{j-1}) where jj is the smallest positive index such that aj=0a_j = 0. Determine if MM is odd or even. The challenge here is to design an algorithm that solves this problem quickly.

Example: if N=5N = 5 and K=3K = 3, then the sequence is (0,3,1,4,2)(0, 3, 1, 4, 2). Its number of inversions MM is 33, which is odd.

Before reading on, I invite you to try a few more examples to get a feel for this problem. See if you can spot a pattern.

Solution

Click to reveal solutionIf you are well trained in elementary number theory, you may have sensed that this problem "smells" number theoretic. Otherwise, you might be surprised to know that this problem is related to quadratic reciprocity! The complete solution can be found here (external link here).

[1] The number of inversions of a sequence of numbers is the minimum number of adjacent swaps required to sort the numbers in non-decreasing order.