Consider a long alley with N doors on one side. All the doors are closed initially. You move to and fro in the alley changing the states of the doors as follows:
- You open a door that is already closed, and you close a door that is already opened.
- You start at one end go on altering the state of the doors till you reach the other end, and then you come back and start altering the states of the doors again.
- In the first go, you alter the states of doors numbered 1, 2, 3, …, N.
- In the second go, you alter the states of doors numbered 2, 4, 6, ….
- In the third go, you alter the states of doors numbered 3, 6, 9 ….
- and so on…
The above procedure will continue till the Nth turn in which you alter the state of the door numbered N. The task is to find the number of open doors at the end of the procedure.
Examples:
Input: N = 3
Output: 1
Input: N = 100
Output: 10
Approach: The given problem can be solved based on the following observations:
- A door can only be open in the end if and only if it has an odd number of factors because each door is visited once by each of its factors.
- Initially, all doors are closed so it will remain closed if it has an even number of factors and will remain open if it has an odd number of factors.
- Therefore, the total number of doors that remain open from 1 to N will be the number of doors that have an odd number of factors.
From the above observations, only the number which is perfect squares having an odd number of factors. Therefore, the total number of doors that remain open from 1 to N will be the number of perfect squares between 1 to N, and the number of perfect squares between 1 to N is sqrt(N).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countOpenDoors( int N)
{
int doorsOpen = sqrt (N);
return doorsOpen;
}
int main()
{
int N = 100;
cout << countOpenDoors(N);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int countOpenDoors( int N)
{
int doorsOpen = ( int ) Math.sqrt(N);
return doorsOpen;
}
public static void main (String[] args) {
int N = 100 ;
System.out.println(countOpenDoors(N));
}
}
|
Python3
import math
def countOpenDoors(N):
doorsOpen = int (math.sqrt(N))
return doorsOpen
if __name__ = = '__main__' :
N = 100
print (countOpenDoors(N))
|
C#
using System;
class GFG {
static int countOpenDoors( int N)
{
int doorsOpen = ( int )Math.Sqrt(N);
return doorsOpen;
}
public static void Main()
{
int N = 100;
Console.Write(countOpenDoors(N));
}
}
|
Javascript
<script>
function countOpenDoors(N) {
let doorsOpen = parseInt(Math.sqrt(N));
return doorsOpen;
}
let N = 100;
document.write(countOpenDoors(N));
</script>
|
Time Complexity: O(log N)
Auxiliary Space: O(1)