Problem for puzzle:
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 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. Test run your program for the following inputs: 1000, 5000, 100000.
The problem I am having is not having an expanding array I think. I could set the array to 10,001, but that would not work for higher numbers. The class I am in is C++ 101, we have not even touched on arrays yet, I am taking the class as a refresher course so I understand a little about them, and figured using an array is my best option. Can any one give me some advice on how to set up an expanding array in this problem?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int lockers[1001];
int numLockers;
int openLockers;
cout << "Please enter the number of Lockers. " << endl;
cin >> numLockers;
for (int i = 1; i <= numLockers; i++)
{
lockers[i] = 0;
}
for (int i = 1; i <= numLockers; i++)
{
for (int j = 1; j <= numLockers; j++)
{
if (j % i == 0)
{
lockers[j] = 1 - lockers[j];
openLockers = 0;
}
}
}
for (int i = 1; i <= numLockers; i++)
{
openLockers += lockers[i];
}
cout << "The number of lockers open are " << openLockers << "." << endl;
return 0;
}
|