collatz.c 512 B

123456789101112131415161718192021222324252627
  1. #include <stdio.h>
  2. int collatz (int n);
  3. int main (int argc, char **argv) {
  4. if (argc < 3) {
  5. printf ("Error; exiting status -1\n");
  6. return -1;
  7. }
  8. int start;
  9. int end = atoi(argv[2]);
  10. int c, temp, max = 0;
  11. for (start = atoi(argv[1]); start <= end; ++start) {
  12. temp = start;
  13. for (c = 1; temp > 1; ++c) {
  14. temp = collatz(temp);
  15. }
  16. if (max < c) { max = c; }
  17. }
  18. printf ("%d\n", max);
  19. }
  20. int collatz (int n) {
  21. if (n == 1) { return 1; }
  22. if (n % 2 == 0) { return n / 2; }
  23. else { return 3 * n + 1; }
  24. }