Skip to content

Commit

Permalink
NativeCalculator::mul() can now handle multiplication natively in mor…
Browse files Browse the repository at this point in the history
…e cases
  • Loading branch information
BenMorel committed Nov 7, 2018
1 parent 43b0b17 commit e794362
Showing 1 changed file with 8 additions and 16 deletions.
24 changes: 8 additions & 16 deletions src/Internal/Calculator/NativeCalculator.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,12 @@
class NativeCalculator extends Calculator
{
/**
* The max number of digits the platform can natively add, subtract or divide without overflow.
* The max number of digits the platform can natively add, subtract, multiply or divide without overflow.
* For multiplication, this represents the max sum of the lengths of both operands.
*
* @var int
*/
private $maxDigitsAddDiv = 0;

/**
* The max number of digits the platform can natively multiply without overflow.
*
* @var int
*/
private $maxDigitsMul = 0;
private $maxDigits = 0;

/**
* Class constructor.
Expand All @@ -36,13 +30,11 @@ public function __construct()
{
switch (PHP_INT_SIZE) {
case 4:
$this->maxDigitsAddDiv = 9;
$this->maxDigitsMul = 4;
$this->maxDigits = 9;
break;

case 8:
$this->maxDigitsAddDiv = 18;
$this->maxDigitsMul = 9;
$this->maxDigits = 18;
break;
}
}
Expand All @@ -62,7 +54,7 @@ public function add(string $a, string $b) : string

$this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg, $aLen, $bLen);

if ($aLen <= $this->maxDigitsAddDiv && $bLen <= $this->maxDigitsAddDiv) {
if ($aLen <= $this->maxDigits && $bLen <= $this->maxDigits) {
return (string) ((int) $a + (int) $b);
}

Expand Down Expand Up @@ -114,7 +106,7 @@ public function mul(string $a, string $b) : string

$this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg, $aLen, $bLen);

if ($aLen <= $this->maxDigitsMul && $bLen <= $this->maxDigitsMul) {
if ($aLen + $bLen <= $this->maxDigits) {
return (string) ((int) $a * (int) $b);
}

Expand Down Expand Up @@ -166,7 +158,7 @@ public function divQR(string $a, string $b) : array

$this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg, $aLen, $bLen);

if ($aLen <= $this->maxDigitsAddDiv && $bLen <= $this->maxDigitsAddDiv) {
if ($aLen <= $this->maxDigits && $bLen <= $this->maxDigits) {
$a = (int) $a;
$b = (int) $b;

Expand Down

0 comments on commit e794362

Please sign in to comment.