function NativeCalculator::doAdd
Performs the addition of two non-signed large integers.
1 call to NativeCalculator::doAdd()
- NativeCalculator::add in vendor/
brick/ math/ src/ Internal/ Calculator/ NativeCalculator.php - Adds two numbers.
File
-
vendor/
brick/ math/ src/ Internal/ Calculator/ NativeCalculator.php, line 272
Class
- NativeCalculator
- Calculator implementation using only native PHP code.
Namespace
Brick\Math\Internal\CalculatorCode
private function doAdd(string $a, string $b) : string {
[
$a,
$b,
$length,
] = $this->pad($a, $b);
$carry = 0;
$result = '';
for ($i = $length - $this->maxDigits;; $i -= $this->maxDigits) {
$blockLength = $this->maxDigits;
if ($i < 0) {
$blockLength += $i;
/** @psalm-suppress LoopInvalidation */
$i = 0;
}
/** @psalm-var numeric-string $blockA */
$blockA = \substr($a, $i, $blockLength);
/** @psalm-var numeric-string $blockB */
$blockB = \substr($b, $i, $blockLength);
$sum = (string) ($blockA + $blockB + $carry);
$sumLength = \strlen($sum);
if ($sumLength > $blockLength) {
$sum = \substr($sum, 1);
$carry = 1;
}
else {
if ($sumLength < $blockLength) {
$sum = \str_repeat('0', $blockLength - $sumLength) . $sum;
}
$carry = 0;
}
$result = $sum . $result;
if ($i === 0) {
break;
}
}
if ($carry === 1) {
$result = '1' . $result;
}
return $result;
}