One hundred students are assigned lockers 1 through 100
The student assigned to locker number 1 opens all 100 lockers
The student assigned to locker number 2 then closes all lockers whose numbers are multiples of 2
The student assigned to locker number 3 toggles the status of all lockers whose numbers are multiples of 3
Locker number 3, which is open gets closed,
Locker number 6, which is closed, gets opened
And so on for as many lockers need to be toggled
The student assigned to locker number 4 toggles the status of all lockers whose numbers are multiples of 4
And so on and on for all 100 students and all 100 lockers
Which lockers will be left open after everyone completes their turns?
Convert this C++ program into x86 assembly language and find out!
#include <iostream>
using namespace std;
// In this case we will be using a global array
// This is not generally the case for any other variables
// 101 element array, all elements initialized to 0
// NOTE: For simplicity, element 0 is unused
int Lockers[101]{ 0 };
// Boolean NOT operation just like the exam question
int NotOperation(int x)
{
return (x == 0) ? 1 : 0;
}
// Student x toggles all lockers { x, 2x, 3x, 4x, ... }
// up to and including locker 100
void StudentTogglingLockers(int x)
{
for (int i = x; i <= 100; i += x)
{
Lockers
= NotOperation(Lockers);
}
}
// 100 students walk through and toggle lockers
void ToggleLockers()
{
for (int i = 1; i <= 100; ++i)
{
StudentTogglingLockers(i);
}
}
void PrintOpenLockers()
{
for (int i = 1; i <= 100; ++i)
{
if (Lockers == 1)
{
cout << i;
cout << ' ';
}
}
cout << endl;
}
int main()
{
ToggleLockers();
PrintOpenLockers();
system("PAUSE");
}