B
B
Bohdan Kalianov2015-07-25 15:58:23
PHP
Bohdan Kalianov, 2015-07-25 15:58:23

How to implement Karatsuba's algorithm for multiplying large numbers in PHP?

In general, I figured out the mathematical component, but there were problems with the practical implementation in php.
For example, for the numbers 1000 and 2000 it works, for the following: Chrome - ERR_EMPTY_RESPONSE.

function foo($x,$y) {
    if (strlen($x) == 1 and strlen($y) == 1)return $x*$y;
    $n = max(strlen($x),strlen($y));

    $n2=$n/2;
    $a = substr($x, 0, floor($n2));
    $b = substr($x, floor($n2));
    $c = substr($y, 0, floor($n2));
    $d = substr($y, floor($n2));
    $p1 = foo($a,$c);
    $p2 = foo($b,$d);
    $p3 = foo($a+$b,$c+$d);
   return ($p1*pow(10,2*($n2)))+($p3-$p1-$p2)*pow(10,$n2)+$p2;
}
echo foo('12345678' , '87654321' );

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Puma Thailand, 2015-07-25
@opium

What are the problems?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question