Advertisement
Shailrshah

The Sword Riddle

Sep 14th, 2014
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.77 KB | None | 0 0
  1. /*100 people standing in a circle in an order 1 to 100. No.1 has a sword. He kills next person (i.e. no. 2) and gives sword to next to next (i.e no.3). Everyone does the same until only 1 survives. Which number survives in the end?*/
  2. #include <stdio.h>
  3. #define N 100
  4. void main(){
  5.     int i=0, j; //i has the sword, j gets killed.
  6.     int a[N]={0}; //0=not killed
  7.     while(1){
  8.         if(i != N-1) j = i + 1;
  9.         else j = 0;
  10.         while(a[j])
  11.             if((j + 1) == N) j = 0; //loop back to 0
  12.             else j++; //skip over the killed people
  13.         if(i==j){ //if i is the only one left, stop
  14.             printf("\n\n\n%d is left!", i+1);
  15.             return;
  16.         }
  17.         a[j] = 1; //kill j
  18.         printf(" %d kills %d.", i+1, j+1);
  19.         if(j != N-1) i = j + 1;
  20.         else i=0;
  21.         while(a[i])
  22.             if((i + 1) == N) i = 0;
  23.             else i++;
  24.     }
  25. }
  26. //73!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement