Consider a set of n boxes with their positions numbered from 1 to n. Initially, all the boxes are CLOSED. These n boxes are subject to modifications over n iterations as follows. At the ith iterations the boxes at the positions whose ids are multiples of i are flipped, i.e. changed from CLOSED to OPEN or vice-versa. For example, at iteration 1, boxes at all positions are flipped, at iteration 2, boxes at positions 2,4,6,etc. are flipped, at iteration 3, boxes at positions 3,6,9, etc. are flipped.
Propose an algorithm to find out, that after n such iterations how many boxes will be OPEN. Note that the answer requires only how many boxes, not their positions. Describe the rationale for the algorithm, give the pseudocode, and its complexity
Initially, all the boxes are CLOSED.
Now a box gets flipped whenever the iteration of its divider comes i.e for example for box number 30 it will be flipped in the iterations 1, 2, 3, 5, 6, 10, 15, 30. Now if we group the divisors we get (1,30), (2,15), (3,10), (5,6) so, the box remains CLOSED. But in case of the perfect square numbers exception occurs because of the pair say for 9, it is (3,3). Therefore, the perfect square numbers between 1 and n will only remain OPEN.
Now the number of perfect squares between 1 and n is floor(sqrt(n)) which can be computed in O(1) time.
Consider a set of n boxes with their positions numbered from 1 to n. Initially, all...