Program to count number of switches that will be on after flipping by n persons in python

PythonServer Side ProgrammingProgramming

Suppose we have a number n, and there are n switches in a room, and all switches are off. Now n people who flip switches as follows −

  • Person 1 flips all switches that are multiples of 1 (so all of the switches).
  • Person 2 flips switches that are multiples of 2 (2, 4, 6, ...)
  • Person i flips switches that are multiples of i.

We have to find the number of switches that will be on at the end.

So, if the input is like n = 5, then the output will be 2, as initially all are off [0, 0, 0, 0, 0], Person 1 flipped all [1, 1, 1, 1, 1], Person 2 flipped like [1, 0, 1, 0, 1], then Person 3 did [1, 0, 0, 0, 0], person 4 did [1, 0, 0, 1, 0]

To solve this, we will follow these steps −

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

Let us see the following implementation to get better understanding −

Example 

Live Demo

class Solution:
   def solve(self, 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

ob = Solution()
n = 5
print(ob.solve(n))

Input

5

Output

2
raja
Updated on 02-Dec-2020 05:12:05

Advertisements