C bootcamp · Lab 37

Collatz steps

mediumWhile Loop12 minLesson: While Loop

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Collatz: if n is even, n = n / 2; if odd, n = 3n + 1. Repeat until n is 1.

Read a starting n and print how many steps it takes. If n is already 1, print 0.

Input. One integer n ≥ 1.

Output. One integer: the step count.

Constraints

  • 1 ≤ n ≤ 10 000

Examples

Example 1 — 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1.
Input
6
Output
8
Example 2
Input
1
Output
0
Hint
  1. while (n != 1) { if (n % 2 == 0) n /= 2; else n = 3 * n + 1; steps++; }
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>

int main(void) {
  long n;
  if (scanf("%ld", &n) != 1) return 1;
  int steps = 0;
  while (n != 1) {
    if (n % 2 == 0) n /= 2;
    else n = 3 * n + 1;
    steps++;
  }
  printf("%d\n", steps);
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.