Skip to content

Instantly share code, notes, and snippets.

@brutuscat
Created July 11, 2013 18:30
Show Gist options
  • Save brutuscat/5977916 to your computer and use it in GitHub Desktop.
Save brutuscat/5977916 to your computer and use it in GitHub Desktop.
PHP Cantor implementation using BCMath extension
<?php
# Need Composer with PHPUnit
require 'vendor/autoload.php';
function cantor($x, $y)
{
// ((x + y) * (x + y + 1)) / 2 + y;
return bcadd(bcdiv(bcmul(bcadd($x, $y), bcadd(bcadd($x, $y), 1)), 2), $y);
}
function uncantor($z)
{
$pair = [];
$t = bcdiv(bcadd(-1, bcsqrt( bcadd(1, bcmul(8, $z)) )), 2);
$pair[0] = bcsub(bcdiv(bcmul($t, bcadd($t, 3)), 2), $z);
$pair[1] = bcsub($z, bcdiv(bcmul($t, bcadd($t, 1)), 2));
return $pair;
}
$x = '1234';
$y = '6789';
$z = cantor($x, $y);
list($xx, $yy) = uncantor($z);
\PHPUnit_Framework_Assert::assertEquals($x, $xx);
\PHPUnit_Framework_Assert::assertEquals($y, $yy);
echo "$x\n";
echo "$y\n";
echo "$z\n";
echo "$xx\n";
echo "$yy\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment