Well, I'm doing the following challenge:
The following iterative sequence is defined by the set of integers positive where:
n - > n / 2 (if n is even) n -> 3n + 1 (if n is odd)
Using the above rules and starting with the number 13, we would generate the following sequence:
13 40 20 10 5 16 8 4 2 1
What can be seen from this sequence (starting at 13 and ending in 1) is that it contains 10 items. Although not yet mathematically proved, is hoping that, given an integer number the sequence will always be 1.
Which positive integer below 1 million produces the sequence with more items?
NOTE: Your code needs to run in less than 5 seconds for the case of 1 million.
But I can not get the script to run in less than 13 seconds.
jpklzm$ time php teste.php
Resposta: 837799
Iterações: 525
real 0m13.737s
user 0m13.203s
sys 0m0.117s
How can I improve the performance of this script?
<?php
$count = 1;
$hicount = 0;
$hicountOwner = 0;
$n = 0;
for($i = 1; $i < 1000000; $i++){
$n = $i;
while($n != 1){
$n = ($n % 2 === 0) ? $n/2 : ($n * 3) + 1;
$count++;
}
if($count > $hicount){
$hicount = $count;
$hicountOwner = $i;
}
$count = 1;
}
echo 'Resposta: ',$hicountOwner,PHP_EOL;
echo 'Iterações: ',$hicount;
?>