Exemple #1
0
function collatz($pos)
{
    print $pos . "\n";
    if ($pos == 1) {
        exit(0);
    } else {
        if ($pos % 2 == 0) {
            collatz($pos / 2);
        } else {
            collatz(3 * $pos + 1);
        }
    }
}
Exemple #2
0
function genChain($num)
{
    global $chains, $longest, $length;
    $x = $num;
    $chains[$x] = $num;
    $num = collatz($num);
    while ($num != 1) {
        if (isset($chains[$num])) {
            $chains[$x] .= "." . $chains[$num];
            $num = 1;
        } else {
            $chains[$x] .= "." . $num;
            $num = collatz($num);
        }
    }
    $len = strlen($chains[$x]);
    if ($len > $length) {
        $length = $len;
        $longest = $x;
    }
}
Exemple #3
0
    } else {
        $next = 3 * $current + 1;
    }
    return $next;
}
function collatz($seed)
{
    $length = 1;
    $next = nextCollatz($seed);
    while ($next > 1) {
        $next = nextCollatz($next);
        $length += 1;
    }
    return $length + 1;
}
echo "<a href='https://projecteuler.net/problem=14'>Project Euler - Problem 14</a>";
echo "<br>";
echo "<br>";
$lengths = array();
$start = 77031;
for ($i = $start; $i < 1000000; $i++) {
    $seed = $i;
    $lengths[] = collatz($seed);
}
$max = max($lengths);
echo "integer with longest sequence: " . ($start + array_search($max, $lengths));
echo "<br>";
echo "length of longest sequence: " . $max;
?>

Exemple #4
0
    echo "{$number} ";
}
echo "<hr>";
function collatz($val)
{
    (yield $val);
    while ($val != 1) {
        if ($val % 2 == 0) {
            $val /= 2;
        } else {
            $val = 3 * $val + 1;
        }
        (yield $val);
    }
}
foreach (collatz(11) as $c) {
    echo $c, " ";
}
//11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
echo "Note how the output values are calculated on the fly and not stored in any array<hr>";
function to_html_list($input)
{
    foreach ($input as $val) {
        (yield "<li>" . $val . "</li>");
    }
}
$arr = array("lorem", "ipsum", "dolor");
foreach (to_html_list($arr) as $val) {
    echo $val, "\n";
}
//This will write out