Monday, 14 December 2020

Zoho Programming question -Locker Problem

 Question

Locker Problem There is a school with 100 students, and correspondingly 100 lockers, all of which start off closed. The first student opens every locker. The second student closes every other locker, starting with the second (2, 4, 6 etc). The third student changes the state of every third locker starting with the third (3,6,9 etc). The fourth would change the status of lockers numbered 4,8,12 etc.,. That is, if the locker is open, it is closed, and if it is closed, it is opened. This continues until all 100 students have passed along the lockers. After the 100th student is done, which lockers are open and which are closed? [Note: program should work for any number of students/lockers]

Logic:

1 4 9 16...

every perfect square will b in open. 


Solution:

import java.util.Scanner;


class Locker {


public static void main(String[] args) {

Scanner scanner=new Scanner(System.in);

int lockerCount,index=2,square=1,open=0;

lockerCount=scanner.nextInt();

while(square<=lockerCount)

{

open++;

square=index*index;

index++;

}

System.out.println("open count"+open+"        close count"+(lockerCount-open));

}


}

Example


100 

open = 10 close = 90 

6456 
open = 80 close = 6376 

4 comments:

  1. Please provide it in c program

    ReplyDelete
    Replies
    1. #include

      int main()
      {
      int lockerCount,square=1,index=1,open=0;
      printf("Enter the lockerCount:\n");
      scanf("%d",&lockerCount);

      while(square <= lockerCount){
      open++;
      index++;
      square = index * index;
      }

      int close = lockerCount - open;

      printf("\nOpen Doors : %d\t Closed Doors : %d",open,close);
      }

      Delete
  2. Author Varshini, you should increment the index before the re-initialization of square inside while loop.

    ReplyDelete
  3. #include
    #include
    int open(int n)
    {
    int res=sqrt(n);
    if(res*res==n)return 1;
    return 0;
    }
    int main()
    {
    int n=100,res=0;
    for(int i=1;i<=n;i++)
    res+=open(i);
    printf("open-%d\nclose-%d",res,n-res);
    return 0;
    }

    ReplyDelete