Counting Necklaces — Solution & Editorial
Burnside's lemma over the rotation group: the answer is (1/N) ∑d|N φ(N/d) Kd. Enumerate divisors in O(√N), compute totients, and divide by N with a modular inverse.
Complexity: O(√N · (log + √))
Watch out: Dividing by N under the modulus needs an inverse (N is coprime to the prime modulus).