Skip to content

Instantly share code, notes, and snippets.

@velnias75
Last active July 16, 2017 04:16
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 velnias75/cf51d5076cfbb91c055e3964caf07066 to your computer and use it in GitHub Desktop.
Save velnias75/cf51d5076cfbb91c055e3964caf07066 to your computer and use it in GitHub Desktop.
PHP implementation of the Karatsuba algorithm (base 10)
<?php
function karatsuba($num1, $num2) {
if(($num1 < 10) || ($num2 < 10)) {
return $num1 * $num2;
}
$m = ceil((max(ceil(log10($num1)), ceil(log10($num2))))/2);
$sn1 = "".$num1;
$high1 = (int)substr($sn1, 0, strlen($sn1) - $m);
$low1 = (int)substr($sn1, -$m);
$sn2 = "".$num2;
$high2 = (int)substr($sn2, 0, strlen($sn2) - $m);
$low2 = (int)substr($sn2, -$m);
$z0 = karatsuba($low1, $low2);
$z1 = karatsuba($low1 + $high1, $low2 + $high2);
$z2 = karatsuba($high1, $high2);
return ($z2 * pow(10, 2 * $m)) + (($z1 - $z2 - $z0) * pow(10, $m)) + $z0;
}
header("Content-type: text/plain");
$n1 = isset($_GET['n1']) ? $_GET['n1'] : mt_rand(0, mt_getrandmax());
$n2 = isset($_GET['n2']) ? $_GET['n2'] : mt_rand(0, mt_getrandmax());
$k = karatsuba($n1, $n2);
printf("%d * %d = %d\n", $n1, $n2, $k);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment