Collatz Steps
JavaScript
Medium
2 views
Problem Description
Given n, apply Collatz until it becomes 1. If n is even: n=n/2 else n=3n+1. Print number of steps. If steps cross 1000000, print -1.
Input Format
One integer n.
Output Format
One integer steps.
Official Solution
const fs=require('fs');const s=fs.readFileSync(0,'utf8').trim();if(!s)process.exit(0);let n=BigInt(s);let steps=0;while(n!==1n && steps<=1000000){if(n%2n===0n)n/=2n;else n=3n*n+1n;steps++;}process.stdout.write(steps>1000000?'-1':String(steps));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!