Computer Programming Contest Preparation

ToolBox - Source for: 1/100/i.c



/home/toolbox/public_html/solutions/1/100/i.c
    1 /* @JUDGE_ID:  823125 100  C  "The 3n+1 problem uses recursive function for cycle computation"*/
    2 /**************
    3  Solution to Problem 100
    4  by: Theodore A. Irra
    5  date: 02/04/2016
    6  **************/
    7 #include <stdio.h>
    8 long process_number(long ); /* see implementation after main */
    9 long cycle; /* potentially perilous global variable but program is short */
   10 int main()
   11 {
   12     long i,j, /* input integers */
   13          num, /* number of integers in the cycle in the range i, j being processed */
   14          low, /* global variable used to determine maximum cycle length */
   15          high, /* as above */
   16          cycle, /* current cycle length so far, initialized to 0 */
   17          cycle_max = 0; /* initial maximum cycle length, initialized to 0 */
   18     while(scanf("%d %d",&i,&j) != EOF)
   19         {
   20             cycle = 0; /* initialize for each integer set */
   21             if(i < j) /* input must be in ascending order */
   22                 {
   23                     low = i;
   24                     high = j;
   25                 }
   26             else
   27                 {
   28                     low = j;
   29                     high = i;
   30                 }
   31             num = low; /* begin with lowest */
   32             cycle_max = cycle; /* initialize */
   33             while (num <= high)
   34                 {
   35                     cycle = process_number(num);  /* function call */
   36                     if (cycle > cycle_max) cycle_max = cycle; /* update result-so-far */
   37                     num++; /* advance one */
   38                 }
   39             printf("%d %d %d\n",i,j,cycle_max);
   40         } /* end while */
   41     return (0);
   42 } /* end main */
   43 long process_number( long n)
   44 /* recursive function that computes the cycle length of integer passed in using the given algorithm*/
   45 {
   46     cycle = 1; /* initialize each time */
   47     if (n == 1) return 1; /* base case */
   48     else
   49         {
   50             if((n % 2) != 0 ) process_number(( 3*n ) + 1); /* conditioinal recursive call*/
   51             else process_number( n/2 ); /* conditional recursive call*/
   52             cycle++; /* update cycle length*/
   53         }
   54     return cycle;
   55 }
   56