Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Check if the door is open or closed
Next article icon

Check if the door is open or closed

Last Updated : 21 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given n doors and n persons. The doors are numbered 1 to n and persons are given id's numbered 1 to n. Each door can have only 2 status open and closed. Initially all the doors have status closed.
Find the final status of all the doors if a person changes the current status of all the doors, i.e. if status open then change to status closed and vice versa, for which he is authorized. A person with id 'i' is authorized to change the status of door numbered 'j' if 'j' is a multiple of 'i'. 

Note: 

  • Initially all the doors have status closed.
  • A person has to change the current status of all the doors for which he is authorized exactly once. 
  • There can be a situation that before a person changes the status of the door, another person who is also authorized for the same door changes the status of the door. 

Example : 

Input 3
Output open closed closed
Explanation
The person with id 1 opens all doors : open open open
id 2 closes the second door : open closed open
id 3 closes the third door : open closed closed

Input 4
Output open closed closed openclosed closed closed
Explanation
The person with id 1 opens all doors : open open open open
id 2 closes the 2nd and 4th doors : open closed open closed
id 3 closes the third door : open closed closed closed
id 4 opens the fourth door : open closed closed open

[Naive Approach] Using Nested Loop – O(n2) time and O(1) space

Each door is toggled once for every divisor of its number. Doors with an odd number of divisors remain open, and doors with an even number of divisors remain closed. Only perfect square doors (1, 4, 9, 16, 25, ...) have an odd number of divisors, so they remain open. Please note that, for every number, divisors appear in pairs. For example, 12 has divisors (1, 12), (3, 4) and (2, 6). For a perfect square, there is a pair that has same values and this makes the number of different divisors odd. For example for 16, divisors are (1, 16), (2, 8) and (4, 4)

C++
#include <iostream> using namespace std;  void printStatusOfDoors(int n) {     for (int i = 1; i <= n; i++) {         int divisors = 0;         for (int j = 1; j <= i; j++) {             if (i % j == 0) {                 divisors++;             }         }         if (divisors % 2 == 0) {             cout << "closed ";         } else {             cout << "open ";         }     } }  int main() {     int n = 5;     printStatusOfDoors(n);     return 0; } 
Java
public class GfG{     public static void printStatusOfDoors(int n) {         for (int i = 1; i <= n; i++) {             int divisors = 0;             for (int j = 1; j <= i; j++) {                 if (i % j == 0) {                     divisors++;                 }             }             if (divisors % 2 == 0) {                 System.out.print("closed ");             } else {                 System.out.print("open ");             }         }     }      public static void main(String[] args) {         int n = 5;         printStatusOfDoors(n);     } } 
Python
def print_status_of_doors(n):     for i in range(1, n + 1):         divisors = 0         for j in range(1, i + 1):             if i % j == 0:                 divisors += 1         if divisors % 2 == 0:             print("closed", end=" ")         else:             print("open", end=" ")  n = 5 print_status_of_doors(n) 
C#
using System;  class GfG{     static void PrintStatusOfDoors(int n) {         for (int i = 1; i <= n; i++) {             int divisors = 0;             for (int j = 1; j <= i; j++) {                 if (i % j == 0) {                     divisors++;                 }             }             if (divisors % 2 == 0) {                 Console.Write("closed ");             } else {                 Console.Write("open ");             }         }     }      static void Main(string[] args) {         int n = 5;         PrintStatusOfDoors(n);     } } 
JavaScript
function printStatusOfDoors(n) {     for (let i = 1; i <= n; i++) {         let divisors = 0;         for (let j = 1; j <= i; j++) {             if (i % j === 0) {                 divisors++;             }         }         if (divisors % 2 === 0) {             process.stdout.write("closed ");         } else {             process.stdout.write("open ");         }     } }  const n = 5; printStatusOfDoors(n); 

Output
open closed closed open closed 

[Expected Approach] Finding Square Root – O(n log(n)) time and O(1) space

We can use Check if count of divisors is even or odd logic to solve the problem effectively.

C++
#include <bits/stdc++.h> using namespace std;  // Function to check whether 'n' // has even number of factors or not bool hasEvenNumberOfFactors(int n) {     int root_n = sqrt(n);      // if 'n' is a perfect square     // it has odd number of factors     if ((root_n*root_n) == n)         return false;      // else 'n' has even     // number of factors     return true; }  // Function to find and print // status of each door void printStatusOfDoors(int n) {     for (int i=1; i<=n; i++)     {         // If even number of factors         // final status is closed         if (hasEvenNumberOfFactors(i))             cout << "closed" << " ";          // else odd number of factors         // final status is open         else             cout << "open" << " ";     } }  // Driver program int main() {     int n = 5;     printStatusOfDoors(n);     return 0; } 
Java
import java.io.*;  class GfG {          // Function to check whether 'n'     // has even number of factors or not     static boolean hasEvenNumberOfFactors(int n)     {         double root_n = Math.sqrt(n);              // if 'n' is a perfect square         // it has odd number of factors         if ((root_n*root_n) == n)             return false;              // else 'n' has even         // number of factors         return true;     }          // Function to find and print     // status of each door     static void printStatusOfDoors(int n)     {         for (int i = 1 ; i <= n; i++)         {             // If even number of factors             // final status is closed             if (hasEvenNumberOfFactors(i))                 System .out.print( "closed" + " ");                  // else odd number of factors             // final status is open             else                 System.out.print( "open" + " ");         }     }          // Driver program     public static void main (String[] args) {         int n = 5;         printStatusOfDoors(n);              } } 
Python
import math  # Function to check whether # 'n' has even number of  # factors or not def hasEvenNumberOfFactors(n):      root_n = math.sqrt(n)       # if 'n' is a perfect square     # it has odd number of factors     if ((root_n * root_n) == n):         return False      # else 'n' has even     # number of factors     return True  # Function to find and print # status of each door def printStatusOfDoors(n):      for i in range(1, n + 1):              # If even number of factors         # final status is closed         if (hasEvenNumberOfFactors(i) == True):             print("closed", end =" ")           # else odd number of factors         # final status is open         else:             print("open", end =" ")       # Driver program n = 5  printStatusOfDoors(n)  
C#
using System;  class GfG {      // Function to check whether     // 'n' has even number of     // factors or not     static bool hasEvenNumberOfFactors(int n)     {         double root_n = Math.Sqrt(n);          // if 'n' is a perfect square         // it has odd number of factors         if ((root_n * root_n) == n)             return false;          // else 'n' has even         // number of factors         return true;     }      // Function to find and print     // status of each door     static void printStatusOfDoors(int n)     {         for (int i = 1; i <= n; i++) {             // If even number of factors             // final status is closed             if (hasEvenNumberOfFactors(i))                 Console.Write("closed"                               + " ");              // else odd number of factors             // final status is open             else                 Console.Write("open"                               + " ");         }     }      // Driver Code     static public void Main()     {         int n = 5;         printStatusOfDoors(n);     } } 
JavaScript
function hasEvenNumberOfFactors(n) {     let root_n = Math.sqrt(n);      // if 'n' is a perfect square     // it has odd number of factors     if ((root_n * root_n) == n)         return false;      // else 'n' has even     // number of factors     return true; }  // Function to find and print // status of each door function printStatusOfDoors(n) {     for (let i = 1; i <= n; i++) {         // If even number of factors         // final status is closed         if (hasEvenNumberOfFactors(i))             console.log("closed" +                         " ");          // else odd number of factors         // final status is open         else             console.log("open" +                         " ");     } }  // Driver Code  let n = 5; printStatusOfDoors(n); 

Output
open closed closed open closed 

Next Article
Check if the door is open or closed

X

xyz
Improve
Article Tags :
  • Misc
  • Mathematical
  • DSA
  • prime-factor
  • TCS
Practice Tags :
  • TCS
  • Mathematical
  • Misc

Similar Reads

    Number of open doors | TCS Coding Question
    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 d
    4 min read
    Check if the robot is within the bounds of the grid after given moves
    Given a grid of size N X M and a robot is placed at cell (N - 1, M - 1). Also, given string str which consists only of the characters 'U' (Up), 'D' (Down), 'L' (Left) and 'R' (Right) representing the moves the robot is going to perform within the grid. The task is to find whether the robot will be s
    9 min read
    Program to check if matrix is lower triangular
    Given a square matrix and the task is to check the matrix is in lower triangular form or not. A square matrix is called lower triangular if all the entries above the main diagonal are zero. Examples: Input : mat[4][4] = {{1, 0, 0, 0}, {1, 4, 0, 0}, {4, 6, 2, 0}, {0, 4, 7, 6}}; Output : Matrix is in
    4 min read
    Maze With N doors and 1 Key
    Given an N * N binary maze where a 0 denotes that the position can be visited and a 1 denotes that the position cannot be visited without a key, the task is to find whether it is possible to visit the bottom-right cell from the top-left cell with only one key along the way. If possible then print "Y
    14 min read
    Check if a key is present in a C++ map or unordered_map
    A C++ map and unordered_map are initialized to some keys and their respective mapped values. Examples: Input : Map : 1 -> 4, 2 -> 6, 4 -> 6Check1 : 5, Check2 : 4Output : 5 : Not present, 4 : PresentC++ implementation : map // CPP code to check if a // key is present in a map #include <bi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences