/*****************************************************************************/
/*									     */
/*  REGENERATE LOOPS							     */
/*  12/28/08 (dkc)							     */
/*									     */
/*  This C program regenerates a loop in the 3n+c sequence given an entry    */
/*  point.								     */
/*									     */
/*****************************************************************************/
#include <stdio.h>
#include <math.h>
int main () {
int c=163;
int s=88;	     // entry point, must be even
unsigned int size=10;	// minimum of 9
int k,max,order,temp;
unsigned int j,n,count,first;
FILE *Outfp;
Outfp = fopen("out0b.dat","w");
//
// compute order (of loop)
//
   k=s;
   max=k;
   if (max<0)
      max=-max;
   while (k==(k/2)*2)
      k=k/2;
   for (j=1; j<10000; j++) {
      k=3*k+c;
      temp=k;
      if (temp<0)
	 temp=-temp;
      if (temp>max)
	 max=temp;
      while (k==(k/2)*2) {
	 if (k==s)
	    goto bskip;
	 k=k/2;
	 }
      }
   printf("error \n");
   goto zskip;
bskip:
   order=3;
   while (order<max)
      order=order*2;
   printf("max=%d, order=%d \n",max,order);
//
// find odd natural number divisible by 3
//
   k=s;
   max=k;
   if (max<0)
      max=-max;
   while (k!=(k/3)*3) {
      if (k==(k/2)*2) {
	 if ((k-c)==((k-c)/3)*3)
	    k=(k-c)/3;
	 else {
	    k=k*2;
	    temp=k;
	    if (temp<0)
	       temp=-temp;
	    if (temp>max)
	       max=temp;
	    }
	 }
      else {
	 k=k*2;
	 temp=k;
	 if (temp<0)
	    temp=-temp;
	 if (temp>max)
	    max=temp;
	 }
      }
   printf("odd divisible by three=%d \n",k);
//
// include even natural numbers to the left of the odd natural number divisible
// by 3
//
   temp=k;
   if (temp<0)
      temp=-temp;
   while (temp<(order/2)) {
      temp=temp*2;
      k=k*2;
      }
//
   n=1;
   count=1;
   fprintf(Outfp," %d",k);
   first=1;
   while (k==(k/2)*2) {
      k=k/2;
      fprintf(Outfp," %d",k);
      n=n+1;
      count=count+1;
      if (n>size) {
	 fprintf(Outfp,"\n");
	 n=0;
	 }
      }
   for (j=1; j<10000; j++) {
      k=3*k+c;
      fprintf(Outfp," %d",k);
      n=n+1;
      count=count+1;
      if (n>size) {
	 fprintf(Outfp,"\n");
	 n=0;
	 }
      while (k==(k/2)*2) {
	 if (k==s) {
	    if (first==1)
	       first=0;
	    else
	       goto askip;
	    }
	 k=k/2;
	 fprintf(Outfp," %d",k);
	 n=n+1;
	 count=count+1;
	 if (n>size) {
	    fprintf(Outfp,"\n");
	    n=0;
	    }
	 }
      }
   fprintf(Outfp,"error \n");
askip:
   fprintf(Outfp,"\n");
   fprintf(Outfp,"order=%d, count=%d \n",order,count-1);
   printf("count=%d \n",count-1);
   printf("\n");
   if (max>order)
      printf("warning:  order=%d, maximum=%d \n",order,max);
zskip:
fclose(Outfp);
return(0);
}