Write a program, solving problem below in any new for you language:
There are 1000 lockers in a high school with 1000 students. The problem begins with the first student opening all 1000 lockers; next the second student closes lockers 2,4,6,8,10 and so on to locker 1000; the third student changes the state (opens lockers closed, closes lockers open) on lockers 3,6,9,12,15 and so on; the fourth student changes the state of lockers 4,8,12,16 and so on. This goes on until every student has had a turn. How many lockers will be open at the end? What is the formula?
Find solution in Dart below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
int numberOfLockers = 1000; | |
// Lockers start all open because of the first student | |
List<String> lockers = new List.filled(numberOfLockers + 1, 'open'); | |
main() { | |
for (var student = 2; student <= numberOfLockers; student++) { | |
// For the student, open the locker if closed, or close if open | |
for (var locker = student; locker <= numberOfLockers; locker += student) { | |
lockers[locker] = lockers[locker] == 'open' ? 'closed' : 'open'; | |
} | |
} | |
// Count of lockers remaining open | |
int total = 0; | |
// List the lockers that remain open | |
for (var locker = 1; locker <= numberOfLockers; locker ++ ) { | |
if (lockers[locker] == 'open') { | |
stdout.write("${locker} "); | |
total += 1; | |
} | |
} | |
print("\nThere are ${total} lockers remaining open."); | |
} | |
// 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 | |
// There are 31 lockers remaining open. |