
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- 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
- Program to count number of ways we can throw n dices in Python
- Program to find minimum number of people to teach in Python
- Write a program in Python to count the number of digits in a given number N
- Program to count the number of ways to distribute n number of candies in k number of bags in Python
- C++ program to count number of operations needed to reach n by paying coins
- Program to count number of points that lie on a line in Python
- Program to count minimum k length sublist that can be flipped to make all items of list to 0 in Python
- Count changes in Led Lights to display digits one by one in C++
- Python program to count total set bits in all number from 1 to n.
- Program to count number of palindromic substrings in Python
- Program to count number of unhappy friends in Python
- Program to count number of homogenous substrings in Python

Advertisements