Documentation

CslibFrontier.Algorithms.WordRAM.AKS.PerfectPower

Perfect-power detection on the word RAM #

Step 1 of the AKS algorithm Agrawal, Kayal, Saxena, Section 4 asks whether n = a ^ b for some b > 1. For n ≥ 2 such an a is at least 2, so b ≤ log₂ n, and n is a b-th power exactly when Nat.nthRoot b n ^ b = n (Cslib.AKS.isPerfectPower_iff_nthRoot). The program computes ⌊log₂ n⌋, and for each b from 2 to ⌊log₂ n⌋ takes the b-th root by binary search (Cslib.Algorithms.WordRAM.NatNthRoot.program) and compares its capped b-th power with n. Every intermediate value is at most n² + 2n + 1.

Main definitions #

Main results #

References #

@[reducible, inline]

The candidate n, preserved.

@[reducible, inline]

The current exponent b.

@[reducible, inline]

The root found by the search.

@[reducible, inline]

Upper end of the search interval.

@[reducible, inline]

Probe of the search.

@[reducible, inline]

Capped power.

@[reducible, inline]

Counter of the capped power.

@[reducible, inline]

Constant one.

@[reducible, inline]

Constant two.

@[reducible, inline]

Loop test of the search.

@[reducible, inline]

⌊log₂ n⌋ + 1, the end of the exponent loop.

@[reducible, inline]

The answer: 1 for a perfect power.

@[reducible, inline]

Argument of the logarithm, consumed.

@[reducible, inline]

⌊log₂ n⌋.

The root search runs on the first ten registers.

The final capped power raises the root lo to the exponent k.

The logarithm runs on larg, lres and the shared constants.

Test one exponent: take the root, raise it back, and record equality with n.

Compute ⌊log₂ n⌋, then test every exponent 2 ≤ b ≤ ⌊log₂ n⌋.

The instruction bound of program, which is O(log³ n).

theorem Cslib.Algorithms.WordRAM.AKS.PerfectPower.exec {w : ℕ} (x : WordRAM.Data 14) (hn : 2 ≤ x.regs n) (hfit : WordRAM.Fits w (x.regs n * x.regs n + 2 * x.regs n + 2)) :

The perfect-power test. For n ≥ 2 and a word size holding n² + 2n + 2, the program leaves 1 in flag if n is a perfect power and 0 otherwise, within time n instructions, preserving n and memory.