1467. Necklaces Up to Rotation

Hard7.5 points estimatedCombinatoricsNumber TheoryMaths

A bead artist threads n beads onto a closed loop, painting each bead with one of k available colours (a colour may be used any number of times, or not at all). The loop can be turned freely, so two threadings that differ only by a rotation count as the same necklace. Flipping the loop over is not allowed.

Return the number of distinct necklaces, modulo 1000000007. Use Burnside's lemma: average, over the n rotations, the number of colourings each rotation leaves unchanged. Group the rotations by divisors of n; factor n once by trial division and aim for about O(sqrt(n) + D log n) time, where D is the number of divisors.

Example 1

Input:
n = 3, k = 2
Output:
4
Explanation:
The 8 colourings of three beads fall into 4 rotation classes: 000, 001, 011 and 111.

Example 2

Input:
n = 4, k = 2
Output:
6
Explanation:
Four beads in two colours give 6 distinct necklaces up to rotation.

Example 3

Input:
n = 1, k = 5
Output:
5
Explanation:
A single bead has one colouring per colour, giving 5 necklaces.

Constraints

1 ≤ n ≤ 109

1 ≤ k ≤ 109

The result is taken modulo 109 + 7.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 800 msC++ 200 msJava 400 msJavaScript 400 msTypeScript 400 ms

Expected complexity

Time
O(sqrt(n) + D log n)
Space
O(D)

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…