Write a PHP program where you take any positive integer n, if n is even, divide it by 2 to get n / 2. If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process until you reach 1
- برمجة بي اتش بي
- 2021-09-10
- mhanasmh00489829403
الأجوبة
<?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));
?>
Sample Output:
Array
(
[0] => 12
[1] => 6
[2] => 3
[3] => 10
[4] => 5
[5] => 16
[6] => 8
[7] => 4
[8] => 2
[9] => 1
)
Array
(
[0] => 19
[1] => 58
[2] => 29
[3] => 88
[4] => 44
[5] => 22
[6] => 11
[7] => 34
[8] => 17
[9] => 52
[10] => 26
[11] => 13
[12] => 40
[13] => 20
[14] => 10
[15] => 5
[16] => 16
[17] => 8
[18] => 4
[19] => 2
[20] => 1
)أسئلة مشابهة
القوائم الدراسية التي ينتمي لها السؤال