Collatz Steps
PHP
Medium
5 views
Problem Description
Starting from n, apply: if even n=n/2 else n=3n+1. Count steps to reach 1.
Input Format
One integer n.
Output Format
One integer steps.
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$n=intval($inputText);
$steps=0;
while($n!==1){
if(($n&1)===0) $n=intdiv($n,2);
else $n=$n*3+1;
$steps++;
}
echo $steps;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!