Steps to reach one

Follow a simple rule until a number reaches 1, and report the journey.

What to build

A program that repeats a rule without knowing how many passes it will need.

Requirements

  • Read a whole number n.
  • While n is not 1: if n is even, divide it by 2; if it is odd, make it 3 * n + 1.
  • Count the steps, and remember the largest value reached, including the starting value.
  • Print steps S peak P.

Input

One whole number n.

Output

One line, as in the example.

Constraints

n is from 1 to 100000.

Example

Input:

5

Output:

steps 5 peak 16

Why it works

The path is 5, 16, 8, 4, 2, 1, which is five steps with a largest value of 16. A while loop fits because the only thing known in advance is the condition to stop.

Examples

Example 1 · Input
5
Expected output
steps 5 peak 16
Example 2 · Input
7
Expected output
steps 16 peak 52

Hints

Hint 1

Use a while loop, because you cannot know the number of steps in advance.

Hint 2

Inside the loop, use n % 2 === 0 to choose between the two rules.

Hint 3

Update the peak after changing n.

Solution

Show one correct solution (try it yourself first)
let n = Number(prompt());
let steps = 0;
let peak = n;
while (n !== 1) {
  if (n % 2 === 0) {
    n = n / 2;
  } else {
    n = 3 * n + 1;
  }
  steps++;
  if (n > peak) {
    peak = n;
  }
}
console.log(`steps ${steps} peak ${peak}`);

Lesson: Loops →