- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- 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 switches that will be on after flipping by n persons in python

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

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

- Related Articles
- Program to count number of on lights flipped by n people in Python
- Program to count number of flipping required to make all x before y in Python
- Program to find remainder after dividing n number of 1s by m in Python
- Program to count number of points that lie on a line 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
- Program to check number of requests that will be processed with given conditions in python
- Program to find shortest sublist so after sorting that entire list will be sorted in Python
- Program to find number of items left after selling n items in python
- Program to count number of unique binary search tree can be formed with 0 to n values in Python
- Program to count number of ways we can throw n dices in Python
- Write a program in Python to count the number of digits in a given number N
- C++ program to count number of operations needed to reach n by paying coins
- Program to count the number of ways to distribute n number of candies in k number of bags in Python
- Count number of bits changed after adding 1 to given N in C++

Advertisements