KatInterview

Lamps After Divisor Sweeps

Math & Bit ManipulationAuto-graded · 19 test cases
EasyAuto-gradedMath & Bit Manipulationmathnumber-theoryperfect-squares

Last updated

Count how many of n switches end up on after sweeping by every step size, which tests the divisor-parity and perfect-square insight.

A corridor has n lamps in a row, numbered 1 through n. All lamps start switched off.

You make n sweeps along the corridor. On sweep k (for k = 1, 2, ..., n), you flip the state of every lamp whose number is a multiple of k. Flipping turns an off lamp on and an on lamp off.

After all n sweeps are done, return how many lamps are on.

Implement a function that takes n and returns this count as an integer. If n is 0, there are no lamps and the answer is 0.

A direct simulation is too slow for large n, so look for the pattern in which lamps end up on.

Constraints

  • 0 <= n <= 10^18
  • n is an integer.
  • The return value is a single integer.

Examples

Example 1

Input: count_lamps_on(3)

Output: 1

Example 2

Input: count_lamps_on(10)

Output: 3

Example 3

Input: count_lamps_on(25)

Output: 5

Hints

Hint 1

Lamp j is flipped once for each sweep k that divides j. Its final state depends only on whether its number of divisors is odd or even.

Hint 2

Divisors normally pair up as (d, j/d). When does a divisor fail to have a distinct partner?

Hint 3

Only perfect squares have an odd number of divisors, so count the perfect squares in 1..n. Use an exact integer square root instead of floating-point sqrt to avoid precision errors for large n.