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
Input
6
Output
8
Input
1
Output
0
Hint
- 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.