- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- Related Questions & Answers
- Program to count number of switches that will be on after flipping by n persons in python
- Program to count number of BST with n nodes in Python
- Program to count number of stepping numbers of n digits in python
- C++ program to count number of operations needed to reach n by paying coins
- Program to find minimum number of people to teach in Python
- Count changes in Led Lights to display digits one by one in C++
- Program to count number of ways we can throw n dices in Python
- Program to count the number of ways to distribute n number of candies in k number of bags in Python
- Write a program in Python to count the number of digits in a given number N
- Program to find modulus of a number by concatenating n times in Python
- Program to count number of points that lie on a line in Python
- Program to find remainder after dividing n number of 1s by m in Python
- Split Array by part base on N count in JavaScript
- Program to find maximum number of people we can make happy in Python
- Count n digit numbers divisible by given number in C++

Advertisements