
If there are 4 bulbs in the room, all initially switched off [ 0, 0, 0, 0 ], we will go through the bulbs ‘4’ times.
In 1st go, All the bulbs will be switched on. [ 1,1, 1, 1 ]
In the 2nd go, 2nd, 4th bulb will be toggled -> [ 1, 0, 1, 0 ]
In the 3rd go, the 3rd bulb will be toggled. -> [ 1, 0. 0, 0 ]
In the 4th go, 4th bulb will be toggled -> [ 1, 0, 0, 1 ].
After ‘N'th go, i.e., 4th go 1st and 4th bulb is switched on. So you have to return 1 and 4.
The first line contains ‘T’, denoting the number of test cases.
The first line of each test case contains ‘ N ‘, denoting the number of bulbs in the room.
For each test case, you need to return the space-separated integers denoting the bulbs’ position that will be switched on.
Print the output of each test case in a separated line.
1 <= T <= 10
1 <= N <= 10^5
Time limit: 1 sec
The simple idea is that we will take an array ‘STATE’ (with all initial values 0), where ‘STATE[ i ]’ = 0 denotes the ‘off’ state of ‘ i-th ‘ bulb and ‘STATE[ i ]’ =1 denotes the ‘on’ state of the ‘ i-th ‘ bulb. We will run a loop of ‘ i ‘ from 1 to ‘N’ and in each iteration, we will toggle all the multiples of ‘i‘. After ‘ N-th ’ go, all the indexes where the value of the ‘STATE’ array is 1 will be our required answer.
The steps are as follows:
In the ‘ i-th ‘ go, we will toggle all the bulbs that are multiples of ‘i‘. Let’s say ‘k‘ be any multiple of ‘i‘, then it will be toggled in ‘ i-th’ go as well as in ‘ k / i’-th go as k / i will also be a multiple of ‘k’. So we can assume that the toggle effect in ‘i'-th go can be canceled by a toggle in ‘ k / i'-th move. In other words, we can say that there will be an even number of toggles for a switch. But this does not hold for perfect square numbers as for perfect square numbers, there will always be odd numbers of toggles.
For Example, bulb number 20 will be toggled in 1st,2nd,4th,5th,10th, and 20th move. But bulb number 16 will be toggled in 1st,2nd,4th,8th,16th move.
We can say the bulbs with an even number of toggles will be switched off at the end, and bulbs with the odd number of toggles will be switched on. So all the bulbs having numbers that are perfect squares will be switched on at the end.
The steps are as follows:
Merge Two Sorted Arrays Without Extra Space
Merge Two Sorted Arrays Without Extra Space
Co-Prime
Day 28 : Fake Coin Problem
Day 28 : Fake Coin Problem
First Digit One
Special Digit Numbers