-
Notifications
You must be signed in to change notification settings - Fork 14
/
Doors.cpp
47 lines (41 loc) · 1010 Bytes
/
Doors.cpp
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
38
39
40
41
42
43
44
45
46
47
// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved.
#include <cassert>
#include <cmath>
#include <deque>
#include <random>
using std::default_random_engine;
using std::deque;
using std::random_device;
using std::uniform_int_distribution;
// @include
bool is_door_open(int i) {
double sqrt_i = sqrt(i);
int floor_sqrt_i = floor(sqrt_i);
return floor_sqrt_i * floor_sqrt_i == i;
}
// @exclude
void check_answer(int n) {
deque<bool> doors(n + 1, false); // false means closed door.
for (int i = 1; i <= n; ++i) {
int start = 0;
while (start + i <= n) {
start += i;
doors[start] = doors[start] ? false : true;
}
}
for (int i = 1; i <= n; ++i) {
assert(is_door_open(i) == doors[i]);
}
}
int main(int argc, char* argv[]) {
default_random_engine gen((random_device())());
int n;
if (argc == 2) {
n = atoi(argv[1]);
} else {
uniform_int_distribution<int> dis(1, 1000);
n = dis(gen);
}
check_answer(n);
return 0;
}