Share Pastebin
Guest
Public paste!

The 3n + 1 problem

By: a guest | Jun 8th, 2010 | Syntax: C | Size: 0.54 KB | Hits: 641 | Expires: Never
Copy text to clipboard
  1. #include <stdio.h>
  2.  
  3. int collatz(int n) {
  4.         int i = 1;
  5.         while(n > 1) {
  6.                 if((n % 2) != 0)
  7.                         n = (3*n) + 1;
  8.                 else
  9.                         n = n/2;
  10.                 ++i;
  11.         }
  12.         return i;
  13. }
  14.  
  15. int main (int argc, char const *argv[])
  16. {
  17.         int i, j;
  18.         while(scanf("%d %d", &i, &j) == 2) {
  19.                 int i2, j2, k;
  20.                 int max = 0;
  21.                
  22.                 if (j < i) {
  23.                         i2 = j;
  24.                         j2 = i;
  25.                 } else {
  26.                         i2 = i;
  27.                         j2 = j;
  28.                 }
  29.                
  30.                 for (k = i2; k <= j2; ++k) {
  31.                         int atual = collatz(k);
  32.                         if (max < atual) {
  33.                                 max = atual;
  34.                         }
  35.                 }
  36.                
  37.                 printf("%d %d %d\n", i, j, max);
  38.         }
  39.         return 0;
  40. }