/* Problem 6--Power Crisis
   This was handled by a simple brute force calculation. */

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char **argv);
int Process (int N, int i);

int main (int argc, char **argv) {

  int r, N, i;
  FILE *in, *out;

 in = fopen ("prob6.in","r");
 out = fopen ("prob6.out","w");
 for (;;) {
  fscanf (in,"%d",&N); /* Get number of regions */
 if (N==0) break;
  i = 1;
  for (;;) { /* Increment random number until 13 is the last one */
  if (13==Process (N,i)) break;
   i++;
  }
  fprintf (out,"%d\n",i);
 }
 fclose (in);
 fclose (out);
 r = EXIT_SUCCESS;
 return r;
}

/* Process accepts the number of regions and the random number and
   computes the last region set. */
int Process (int N, int i) {

  int j, *A, k, l;

 A = malloc (N*sizeof (int));
 j = 0;
 for (;;) {
 if (j==N) break; /* Initialize array of booleans to 0 */
  A[j] = 0;
  j++;
 }
 A[0] = 1; /* Region 1 is always the first one visited */
 j = 1;
 k = 1;
 for (;;) { /* Compute the N regions one by one */
 if (j==N) break;
  l = 0; /* Visit i empty squares */
  for (;;) {
  if (l==i) break;
   if (!A[k]) {
    l++;
   } else {
   }
   k = (k+1)%N;
  }
  A[(k+N-1)%N] = 1; /* Mark the ith. empty square we found */
  j++;
 }
 free (A);
 if (k==0) {
  k = N;
 } else {
 }
 return k; /* What was the last one visited? */
}
