C++ bootcamp · Lab 39

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 line: an integer n ≥ 1.

Output. One integer: the step count.

Constraints

  • 1 ≤ n ≤ 10000

Examples

Example 1 — 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1.
Input
6
Output
8
Example 2
Input
1
Output
0
Hint
  1. Use long long — 3n + 1 can grow before it falls.
  2. while (n != 1) { n = n % 2 == 0 ? n / 2 : 3 * n + 1; steps++; }
Show correct code

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

#include <iostream>

int main() {
  long long n;
  std::cin >> n;
  int steps = 0;
  while (n != 1) {
    n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
    steps++;
  }
  std::cout << steps << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.