programming-examples/php/Basics/PHP program where you take any positive integer n, if n is even, divide it by 2 to get n (by) 2..php

26 lines
420 B
PHP
Raw Permalink Normal View History

2019-11-18 14:44:36 +01:00
<?php
function collatz_sequence($x)
{
$num_seq = [$x];
if ($x < 1)
{
return [];
}
while ($x > 1)
{
if ($x % 2 == 0)
{
$x = $x / 2;
}
else
{
$x = 3 * $x + 1;
}
# Added line
array_push($num_seq, $x);
}
return $num_seq;
}
print_r(collatz_sequence(12));
print_r(collatz_sequence(19));
?>