[ create a new paste ] login | about

Link: http://codepad.org/gN5ir4Qf    [ raw code | output | fork | 4 comments ]

mohit_at_codepad - C++, pasted on Jul 26:
/// Problem statement: There are n doors and n students.
/// Initially all doors are closed.
/// Then each student goes and perform the following
/// kth student toggle door number k, 2k, 3k .... etc
/// For ex: Student 1 toggles all door (If it is open, close it and vice-versa)
///         Student 2 toggles door number 2, 4, 6, .... 96, 98, 100
///         ...
/// Find the number of open doors if the number of students is 100
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
  const int numDoors = 100;
  bool doors[numDoors];
  for(int i = 1; i <= numDoors; ++i) doors[i-1] = i > numDoors / 2;
  for(int i = 1; i <=  numDoors / 2; ++i) {
    for(int j = i; j <= numDoors; j += i) {
      doors[j-1] ^= true;
    }
  }
  cout << "Number of open doors = " << count( doors, doors + numDoors, true ) << endl;
}


Output:
1
Number of open doors = 10


Create a new paste based on this one


Comments:
posted by mohit_at_codepad on Jul 26
reply
posted by mohit_at_codepad on Jul 26
I guess it is floor value of squareroot.
reply
posted by mohit_at_codepad on Jul 28
Simple reasoning can tell that no matter how many students are there, only gate number 1, 4, 9, 16... are open and rest all are closed.
reply
posted by mohit_at_codepad on Jul 28
If you list all the multiples of a number n they are
n is divided by 1, k1, k2...km, n/km, ... n/k2, n/k1, n/1 (where km < sqrt(n), If n is not a perfect square)
So the number of multiples are even which means the door is not toggled

n is divided by 1, k1, k2...km, ... n/k2, n/k1, n/1 (where km = sqrt(n), if n is perfect square. In this case km = n/km so it has no pair causing odd number of terms and thus door is toggled)
reply