Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@stuartlangridge
Created July 19, 2022 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartlangridge/fc96f20b495b10aff073ab95e810915a to your computer and use it in GitHub Desktop.
Save stuartlangridge/fc96f20b495b10aff073ab95e810915a to your computer and use it in GitHub Desktop.
PHP version of imul
# this file is $a, $b, expected answer for imul($a, $b)
$ cat tests/imul.txt
2,4,8
1,1,1
10,10,100
-1, -2, 2
1, 2, 2
-1, 2, -2
1, -2, -2
-0, 0, 0
0, -0, 0
-1, -0, 0
1, -0, 0
4294967295, 1, -1
4294967295, 4294967295, 1
4294967295, -4294967295, -1
4294967295, 4294967294, 2
4294967295, -4294967294, -2
65536, 65536, 0
# this checks that file in PHP and in Deno JS. JS gets them all right.
$ bash tests/run.sh
php failure: imul(4294967295, 4294967295) returned 1, should be 0
php failure: imul(4294967295, -4294967295) returned -1, should be 0
php failure: imul(4294967295, 4294967294) returned 2, should be 0
php failure: imul(4294967295, -4294967294) returned -2, should be 0
php imul successes: 13, failures: 4
js imul successes: 17, failures 0
$ cat test/test_maths.php
<?php
require(dirname(__FILE__) . "/../maths.php");
$imul = file_get_contents(dirname(__FILE__) . "/imul.txt");
$lines = explode("\n", $imul);
$successes = 0; $failures = 0;
foreach ($lines as $line) {
$parts = explode(",", $line);
if (count($parts) == 3) {
$a = intval($parts[0]);
$b = intval($parts[1]);
$answer = intval($parts[2]);
$try = imul($a, $b);
if ($try == $answer) {
$successes += 1;
} else {
$failures += 1;
echo "php failure: imul($a, $b) returned $answer, should be $try\n";
}
}
}
echo("php imul successes: $successes, failures: $failures\n");
?>
$ cat test/maths.php
<?php
function imul($a, $b) {
$c = ($a * $b) % (2**32);
if ($c >= 2**31) $c -= 2**32;
return $c;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment