28,104 views
14 votes
14 votes
A high school has 1000 students and 1000 lockers, one locker for each student. On the first day of school, the principal plays the following game: She asks the first student to go and open all the lockers. She then asks the second student to go and close all the even-numbered lockers. The third student is asked to check every third locker. If it is open, the student closes it; if it is closed, the student opens it. The fourth student is asked to check every fourth locker. If it is open, the student closes it; if it is closed, the student opens it. The remaining students continue this game. In general, the nth student checks every nth locker. If the locker is open, the student closes it; if it is closed, the student opens it. After all the students have taken their turn, some of the lockers are open and some are closed. Write a C++ program that prompts the user to enter the number of lockers in a school. After the game is over, the program outputs the number of lockers that are opened.

User Alexey Berezkin
by
2.3k points

1 Answer

13 votes
13 votes

#include <bits/stdc++.h>

static int counter=0;

int check_locker(int num) {

//Pass the first student. All lockers are open.

std::vector<int> lockers(num,1);

//Second student. Close the even locker(s).

for(int i=1;i<=lockers.size();i++) {

if(i%2==0) {

lockers.at(i-1)=0;

} else {

;;

}

}

//Each n. student will check.

for(int j=3; j<=lockers.size();j++) {

for(int m=j; m<=lockers.size();m+=j) {

if(lockers.at(m-1)==1) lockers.at(m-1)=0;

else lockers.at(m-1) = 1;

}

}

//Count 1's

for(auto& c:lockers) {

if(c==1) counter++;

else ;;

}

/*For debug purposes, if you want to print the locker's status, activate!

for(auto& p:lockers) {

std::cout << p << " ";

}

*/

return counter;

}

int main(int argc, char* argv[]) {

//Get the amount of lockers from user.

std::cout << "How many lockers does the school have?: ";

int idx; std::cin>>idx;

//Waiting..

std::cout << "Evaluating..\\";

std::this_thread::sleep_for(std::chrono::milliseconds(1000));

//Send data into check_locker()

std::cout << "There is/are " << check_locker(idx) << " open locker(s)." << std::endl;

return 0;

}

A high school has 1000 students and 1000 lockers, one locker for each student. On-example-1
User FcoRodr
by
3.0k points