Program to count number of on lights flipped by n people in Python


Suppose we have a number n, consider there are n toggle switches in a room and there are n people present in that room, they flip switches as follows −

  • Person 1 comes and flips all switches.
  • Person 2 comes and flips switches that are multiples of 2: 2, 4, 6, ...
  • Person i comes and flips switches that are multiples of i. and so on.

We have to find the number of switches that will be in on position finally.

So, if the input is like n = 5, then the output will be 2, as initially bulbs are [0, 0, 0, 0, 0].

  • After player 1: [1, 1, 1, 1, 1]
  • After player 2: [1, 0, 1, 0, 1]
  • After player 3: [1, 0, 0, 0, 1]
  • After player 4: [1, 0, 0, 1, 1]
  • After player 5: [1, 0, 0, 1, 0]

At the end there are 2 lights are in ON state

To solve this, we will follow these steps −

  • l := 0
  • r := n
  • while l <= r, do
    • mid := l + floor of (r - l)/2
    • if mid * mid <= n < (mid + 1)^2, then
      • return mid
    • otherwise when n < mid^2, then
      • r := mid
    • otherwise,
      • l := mid + 1

Example

Let us see the following implementation to get better understanding −

def solve(n):
   l, r = 0, n
   while l <= r:
      mid = l + (r - l) // 2
      if mid * mid <= n < (mid + 1) * (mid + 1):
         return mid
      elif n < mid * mid:
         r = mid
      else:
         l = mid + 1

n = 5
print(solve(n))

Input

5

Output

2

Updated on: 19-Oct-2021

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements