enamsustcse

100 The 3n + 1 problem

May 1st, 2012
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.73 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int cycle_length (int n);
  4.  
  5. int main()
  6. {
  7.     int i, j, k, large, n, p, q;
  8.  
  9.     while(scanf("%d %d", &i, &j) == 2)
  10.     {
  11.         if (i > 0 && j > 0)
  12.         {
  13.             q = i > j ? i : j;
  14.             p = i < j ? i : j;
  15.             large = 0;
  16.             for (k = p; k <= q; k++)
  17.             {
  18.                 n = cycle_length(k);
  19.                 if (n > large) large = n;
  20.             }
  21.             printf("%d %d %d\n", i, j, large);
  22.         }
  23.     }
  24.     return 0;
  25. }
  26.  
  27. int cycle_length(int x)
  28. {
  29.     int i;
  30.     if(x != 1)
  31.     {
  32.         for (i = 1; x != 1; ++i)
  33.         {
  34.             if (x % 2 == 1) x = (3 * x + 1);
  35.             else x = x / 2;
  36.         }
  37.     }
  38.     else i = 1;
  39.     return i;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment