Promi_38

toggling doors

Jan 1st, 2021
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. /* You have 100 doors in a row that are all initially closed. You make 100 passes by the doors starting with the first door every time. The first time through you visit every door and toggle the door(if the door is closed, you open it, otherwise you will close the door. The second time you will visit oevery 2nd door, third time every 3rd door, etc. until you only visit the 100th door. What state are the doors in after the last pass? Which are open and which are closed? */
  2.  
  3.  
  4. #include<stdio.h>
  5. #include<string.h>
  6.  
  7. int main()
  8. {
  9.     char s[] = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";
  10.    
  11.     int i, j;
  12.     for(i = 0; i < strlen(s); i++)
  13.     {
  14.         for(j = 0; j < strlen(s); j++)
  15.         {
  16.             if((j+1) % (i+1) == 0)
  17.             {
  18.                 if(s[j] == 'c') s[j] = 'o';
  19.                 else s[j] = 'c';
  20.             }
  21.         }
  22.     }
  23.    
  24.     for(i = 0; i < strlen(s); i++)
  25.     {
  26.         if(s[i] == 'o')
  27.         {
  28.             if(i + 1 == 1) printf("%dst, ", i+1);
  29.             else if(i + 1 == 3) printf("%drd, ", i+1);  //only perfect square doors
  30.             else if printf("%dth, ", i+1);
  31.         }
  32.     }
  33.    
  34.     printf("doors will be opened in the end\n");
  35.     printf("%s\n", s);
  36. }
  37.  
  38.  
  39. /*Explanation:
  40.     - A door is toggled in the ith walk if i divides door number. For example, door number 45 is toggled in 1st, 3rd, 5th, 9th, 15th walk.
  41.     - The door is switched back to initial stage for every pair of divisors. For example, 45 is toggled 6 times for 3 pairs (5, 9), (15, 3) and (1, 45)
  42.     - Primarily, it looks like, all of the doors would become closed at the end. But for example 16, the pair (4, 4) means only one walk. Same case will happen for other perfect square numbers.*/
Advertisement
Add Comment
Please, Sign In to add comment