20191217

Collatz Conjeture in PHP

I've made some versions of the Collatz Conjeture in PHP, this is the most simple, it didn't use any array storage to avoid filling the computer memory.

It takes 163 seconds in my MacBook to test first 10.000.000 integers.

Sample output (after 163 seconds):
ENDED CHECKING UNTIL 10000000 in 163 seconds (61349.693251534 numbers per second)


$limit=10000000;
$i=2;
$checked=array();
$start=time();

while ($i<=$limit)
{
    //echo "$i : ";
    if (!collatz($i))
    {
        echo "$i NO!\n";
        die;
    }   
    $i++;
}
echo "\n";

$end=time();
$elapsed=$end-$start;
$numbers_per_second=$limit;
if ($elapsed>0) $numbers_per_second=$limit/$elapsed;

echo "ENDED CHECKING UNTIL $limit in $elapsed seconds ($numbers_per_second numbers per second)\n";

function collatz ($i)
{
    if ($i==1) return true;

    //echo "$i,";
    if ($i%2==0)
    {// par
        $i=collatz($i/2);
    }
    else
    {// impar
        $i=collatz(($i*3)+1);
    }
    return $i;
}


Collatz Conjeture in Rust

As a test of Rust language I've done a simple Rust checker from 1 to 10.000.000 it takes 18 seconds in my MacBook.

Sample output (after 18 seconds):
10000000 numbers checked in 18 seconds (555555 numbers per second)

use std::process::exit;
use std::time::Instant;

fn main() {
    let mut i=1;
    let start = Instant::now();

    while i<=10000000
    {
        let res=collatz(i);
        if res
        {
            i=i+1;
        }
        else
        {
            println!("{} NO!!!", i);
            exit(1);
        }
    }
    let elapsed=start.elapsed().as_secs();
    println!("{} numbers checked in {} seconds ({} numbers per second)", i-1, elapsed, (i-1)/elapsed);
}

fn collatz(i: u64) -> bool
{
    let mut res;
    res=false;

    if i==1
    {
        res=true
    }
    else
    {
        if i%2==0
        {// par
            res=collatz(i/2);
        }
        else
        {// impar
            res=collatz((i*3)+1);
        }
    }
    res
}