• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

brick / math / 21598325800

02 Feb 2026 04:26PM UTC coverage: 99.287% (-0.08%) from 99.363%
21598325800

push

github

BenMorel
Minor documentation tweaks

1253 of 1262 relevant lines covered (99.29%)

2507.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.31
/src/Internal/Calculator/NativeCalculator.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Brick\Math\Internal\Calculator;
6

7
use Brick\Math\Internal\Calculator;
8
use Override;
9

10
use function assert;
11
use function in_array;
12
use function intdiv;
13
use function is_int;
14
use function ltrim;
15
use function str_pad;
16
use function str_repeat;
17
use function strcmp;
18
use function strlen;
19
use function substr;
20

21
use const PHP_INT_SIZE;
22
use const STR_PAD_LEFT;
23

24
/**
25
 * Calculator implementation using only native PHP code.
26
 *
27
 * @internal
28
 */
29
final readonly class NativeCalculator extends Calculator
30
{
31
    /**
32
     * The max number of digits the platform can natively add, subtract, multiply or divide without overflow.
33
     * For multiplication, this represents the max sum of the lengths of both operands.
34
     *
35
     * In addition, it is assumed that an extra digit can hold a carry (1) without overflowing.
36
     * Example: 32-bit: max number 1,999,999,999 (9 digits + carry)
37
     *          64-bit: max number 1,999,999,999,999,999,999 (18 digits + carry)
38
     */
39
    private int $maxDigits;
40

41
    /**
42
     * @pure
43
     *
44
     * @codeCoverageIgnore
45
     */
46
    public function __construct()
47
    {
48
        $this->maxDigits = match (PHP_INT_SIZE) {
49
            4 => 9,
50
            8 => 18,
51
        };
52
    }
53

54
    #[Override]
55
    public function add(string $a, string $b): string
56
    {
57
        /**
58
         * @var numeric-string $a
59
         * @var numeric-string $b
60
         */
61
        $result = $a + $b;
7,857✔
62

63
        if (is_int($result)) {
7,857✔
64
            return (string) $result;
4,353✔
65
        }
66

67
        if ($a === '0') {
5,161✔
68
            return $b;
4,113✔
69
        }
70

71
        if ($b === '0') {
5,120✔
72
            return $a;
×
73
        }
74

75
        [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
5,120✔
76

77
        $result = $aNeg === $bNeg ? $this->doAdd($aDig, $bDig) : $this->doSub($aDig, $bDig);
5,120✔
78

79
        if ($aNeg) {
5,120✔
80
            $result = $this->neg($result);
121✔
81
        }
82

83
        return $result;
5,120✔
84
    }
85

86
    #[Override]
87
    public function sub(string $a, string $b): string
88
    {
89
        return $this->add($a, $this->neg($b));
4,721✔
90
    }
91

92
    #[Override]
93
    public function mul(string $a, string $b): string
94
    {
95
        /**
96
         * @var numeric-string $a
97
         * @var numeric-string $b
98
         */
99
        $result = $a * $b;
7,264✔
100

101
        if (is_int($result)) {
7,264✔
102
            return (string) $result;
4,221✔
103
        }
104

105
        if ($a === '0' || $b === '0') {
4,280✔
106
            return '0';
7✔
107
        }
108

109
        if ($a === '1') {
4,275✔
110
            return $b;
6✔
111
        }
112

113
        if ($b === '1') {
4,275✔
114
            return $a;
×
115
        }
116

117
        if ($a === '-1') {
4,275✔
118
            return $this->neg($b);
12✔
119
        }
120

121
        if ($b === '-1') {
4,263✔
122
            return $this->neg($a);
1✔
123
        }
124

125
        [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
4,262✔
126

127
        $result = $this->doMul($aDig, $bDig);
4,262✔
128

129
        if ($aNeg !== $bNeg) {
4,262✔
130
            $result = $this->neg($result);
108✔
131
        }
132

133
        return $result;
4,262✔
134
    }
135

136
    #[Override]
137
    public function divQ(string $a, string $b): string
138
    {
139
        return $this->divQR($a, $b)[0];
6,523✔
140
    }
141

142
    #[Override]
143
    public function divR(string $a, string $b): string
144
    {
145
        return $this->divQR($a, $b)[1];
1,964✔
146
    }
147

148
    #[Override]
149
    public function divQR(string $a, string $b): array
150
    {
151
        if ($a === '0') {
9,622✔
152
            return ['0', '0'];
123✔
153
        }
154

155
        if ($a === $b) {
9,585✔
156
            return ['1', '0'];
519✔
157
        }
158

159
        if ($b === '1') {
9,523✔
160
            return [$a, '0'];
615✔
161
        }
162

163
        if ($b === '-1') {
9,487✔
164
            return [$this->neg($a), '0'];
281✔
165
        }
166

167
        /** @var numeric-string $a */
168
        $na = $a * 1; // cast to number
9,460✔
169

170
        if (is_int($na)) {
9,460✔
171
            /** @var numeric-string $b */
172
            $nb = $b * 1;
5,062✔
173

174
            if (is_int($nb)) {
5,062✔
175
                // the only division that may overflow is PHP_INT_MIN / -1,
176
                // which cannot happen here as we've already handled a divisor of -1 above.
177
                $q = intdiv($na, $nb);
4,933✔
178
                $r = $na % $nb;
4,933✔
179

180
                return [
4,933✔
181
                    (string) $q,
4,933✔
182
                    (string) $r,
4,933✔
183
                ];
4,933✔
184
            }
185
        }
186

187
        [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
5,932✔
188

189
        [$q, $r] = $this->doDiv($aDig, $bDig);
5,932✔
190

191
        if ($aNeg !== $bNeg) {
5,932✔
192
            $q = $this->neg($q);
749✔
193
        }
194

195
        if ($aNeg) {
5,932✔
196
            $r = $this->neg($r);
687✔
197
        }
198

199
        return [$q, $r];
5,932✔
200
    }
201

202
    #[Override]
203
    public function pow(string $a, int $e): string
204
    {
205
        if ($e === 0) {
560✔
206
            return '1';
×
207
        }
208

209
        if ($e === 1) {
560✔
210
            return $a;
560✔
211
        }
212

213
        $odd = $e % 2;
560✔
214
        $e -= $odd;
560✔
215

216
        $aa = $this->mul($a, $a);
560✔
217

218
        $result = $this->pow($aa, $e / 2);
560✔
219

220
        if ($odd === 1) {
560✔
221
            $result = $this->mul($result, $a);
449✔
222
        }
223

224
        return $result;
560✔
225
    }
226

227
    /**
228
     * Algorithm from: https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/.
229
     */
230
    #[Override]
231
    public function modPow(string $base, string $exp, string $mod): string
232
    {
233
        // normalize to Euclidean representative so modPow() stays consistent with mod()
234
        $base = $this->mod($base, $mod);
58✔
235

236
        // special case: the algorithm below fails with 0 power 0 mod 1 (returns 1 instead of 0)
237
        if ($base === '0' && $exp === '0' && $mod === '1') {
58✔
238
            return '0';
3✔
239
        }
240

241
        // special case: the algorithm below fails with power 0 mod 1 (returns 1 instead of 0)
242
        if ($exp === '0' && $mod === '1') {
55✔
243
            return '0';
×
244
        }
245

246
        $x = $base;
55✔
247

248
        $res = '1';
55✔
249

250
        // numbers are positive, so we can use remainder instead of modulo
251
        $x = $this->divR($x, $mod);
55✔
252

253
        while ($exp !== '0') {
55✔
254
            if (in_array($exp[-1], ['1', '3', '5', '7', '9'])) { // odd
53✔
255
                $res = $this->divR($this->mul($res, $x), $mod);
53✔
256
            }
257

258
            $exp = $this->divQ($exp, '2');
53✔
259
            $x = $this->divR($this->mul($x, $x), $mod);
53✔
260
        }
261

262
        return $res;
55✔
263
    }
264

265
    /**
266
     * Adapted from https://cp-algorithms.com/num_methods/roots_newton.html.
267
     */
268
    #[Override]
269
    public function sqrt(string $n): string
270
    {
271
        if ($n === '0') {
5,548✔
272
            return '0';
10✔
273
        }
274

275
        // initial approximation
276
        $x = str_repeat('9', intdiv(strlen($n), 2) ?: 1);
5,538✔
277

278
        $decreased = false;
5,538✔
279

280
        for (; ;) {
281
            $nx = $this->divQ($this->add($x, $this->divQ($n, $x)), '2');
5,538✔
282

283
            if ($x === $nx || $this->cmp($nx, $x) > 0 && $decreased) {
5,538✔
284
                break;
5,538✔
285
            }
286

287
            $decreased = $this->cmp($nx, $x) < 0;
5,528✔
288
            $x = $nx;
5,538✔
289
        }
290

291
        return $x;
5,538✔
292
    }
293

294
    /**
295
     * Performs the addition of two non-signed large integers.
296
     *
297
     * @pure
298
     */
299
    private function doAdd(string $a, string $b): string
300
    {
301
        [$a, $b, $length] = $this->pad($a, $b);
4,961✔
302

303
        $carry = 0;
4,961✔
304
        $result = '';
4,961✔
305

306
        for ($i = $length - $this->maxDigits; ; $i -= $this->maxDigits) {
4,961✔
307
            $blockLength = $this->maxDigits;
4,961✔
308

309
            if ($i < 0) {
4,961✔
310
                $blockLength += $i;
4,928✔
311
                $i = 0;
4,928✔
312
            }
313

314
            /** @var numeric-string $blockA */
315
            $blockA = substr($a, $i, $blockLength);
4,961✔
316

317
            /** @var numeric-string $blockB */
318
            $blockB = substr($b, $i, $blockLength);
4,961✔
319

320
            $sum = (string) ($blockA + $blockB + $carry);
4,961✔
321
            $sumLength = strlen($sum);
4,961✔
322

323
            if ($sumLength > $blockLength) {
4,961✔
324
                $sum = substr($sum, 1);
4,607✔
325
                $carry = 1;
4,607✔
326
            } else {
327
                if ($sumLength < $blockLength) {
4,961✔
328
                    $sum = str_repeat('0', $blockLength - $sumLength) . $sum;
4,537✔
329
                }
330
                $carry = 0;
4,961✔
331
            }
332

333
            $result = $sum . $result;
4,961✔
334

335
            if ($i === 0) {
4,961✔
336
                break;
4,961✔
337
            }
338
        }
339

340
        if ($carry === 1) {
4,961✔
341
            $result = '1' . $result;
3,112✔
342
        }
343

344
        return $result;
4,961✔
345
    }
346

347
    /**
348
     * Performs the subtraction of two non-signed large integers.
349
     *
350
     * @pure
351
     */
352
    private function doSub(string $a, string $b): string
353
    {
354
        if ($a === $b) {
4,168✔
355
            return '0';
3,415✔
356
        }
357

358
        // Ensure that we always subtract to a positive result: biggest minus smallest.
359
        $cmp = $this->doCmp($a, $b);
4,158✔
360

361
        $invert = ($cmp === -1);
4,158✔
362

363
        if ($invert) {
4,158✔
364
            $c = $a;
40✔
365
            $a = $b;
40✔
366
            $b = $c;
40✔
367
        }
368

369
        [$a, $b, $length] = $this->pad($a, $b);
4,158✔
370

371
        $carry = 0;
4,158✔
372
        $result = '';
4,158✔
373

374
        $complement = 10 ** $this->maxDigits;
4,158✔
375

376
        for ($i = $length - $this->maxDigits; ; $i -= $this->maxDigits) {
4,158✔
377
            $blockLength = $this->maxDigits;
4,158✔
378

379
            if ($i < 0) {
4,158✔
380
                $blockLength += $i;
4,157✔
381
                $i = 0;
4,157✔
382
            }
383

384
            /** @var numeric-string $blockA */
385
            $blockA = substr($a, $i, $blockLength);
4,158✔
386

387
            /** @var numeric-string $blockB */
388
            $blockB = substr($b, $i, $blockLength);
4,158✔
389

390
            $sum = $blockA - $blockB - $carry;
4,158✔
391

392
            if ($sum < 0) {
4,158✔
393
                $sum += $complement;
4,112✔
394
                $carry = 1;
4,112✔
395
            } else {
396
                $carry = 0;
4,158✔
397
            }
398

399
            $sum = (string) $sum;
4,158✔
400
            $sumLength = strlen($sum);
4,158✔
401

402
            if ($sumLength < $blockLength) {
4,158✔
403
                $sum = str_repeat('0', $blockLength - $sumLength) . $sum;
4,125✔
404
            }
405

406
            $result = $sum . $result;
4,158✔
407

408
            if ($i === 0) {
4,158✔
409
                break;
4,158✔
410
            }
411
        }
412

413
        // Carry cannot be 1 when the loop ends, as a > b
414
        assert($carry === 0);
415

416
        $result = ltrim($result, '0');
4,158✔
417

418
        if ($invert) {
4,158✔
419
            $result = $this->neg($result);
40✔
420
        }
421

422
        return $result;
4,158✔
423
    }
424

425
    /**
426
     * Performs the multiplication of two non-signed large integers.
427
     *
428
     * @pure
429
     */
430
    private function doMul(string $a, string $b): string
431
    {
432
        $x = strlen($a);
4,262✔
433
        $y = strlen($b);
4,262✔
434

435
        $maxDigits = intdiv($this->maxDigits, 2);
4,262✔
436
        $complement = 10 ** $maxDigits;
4,262✔
437

438
        $result = '0';
4,262✔
439

440
        for ($i = $x - $maxDigits; ; $i -= $maxDigits) {
4,262✔
441
            $blockALength = $maxDigits;
4,262✔
442

443
            if ($i < 0) {
4,262✔
444
                $blockALength += $i;
3,980✔
445
                $i = 0;
3,980✔
446
            }
447

448
            $blockA = (int) substr($a, $i, $blockALength);
4,262✔
449

450
            $line = '';
4,262✔
451
            $carry = 0;
4,262✔
452

453
            for ($j = $y - $maxDigits; ; $j -= $maxDigits) {
4,262✔
454
                $blockBLength = $maxDigits;
4,262✔
455

456
                if ($j < 0) {
4,262✔
457
                    $blockBLength += $j;
4,008✔
458
                    $j = 0;
4,008✔
459
                }
460

461
                $blockB = (int) substr($b, $j, $blockBLength);
4,262✔
462

463
                $mul = $blockA * $blockB + $carry;
4,262✔
464
                $value = $mul % $complement;
4,262✔
465
                $carry = ($mul - $value) / $complement;
4,262✔
466

467
                $value = (string) $value;
4,262✔
468
                $value = str_pad($value, $maxDigits, '0', STR_PAD_LEFT);
4,262✔
469

470
                $line = $value . $line;
4,262✔
471

472
                if ($j === 0) {
4,262✔
473
                    break;
4,262✔
474
                }
475
            }
476

477
            if ($carry !== 0) {
4,262✔
478
                $line = $carry . $line;
4,181✔
479
            }
480

481
            $line = ltrim($line, '0');
4,262✔
482

483
            if ($line !== '') {
4,262✔
484
                $line .= str_repeat('0', $x - $blockALength - $i);
4,262✔
485
                $result = $this->add($result, $line);
4,262✔
486
            }
487

488
            if ($i === 0) {
4,262✔
489
                break;
4,262✔
490
            }
491
        }
492

493
        return $result;
4,262✔
494
    }
495

496
    /**
497
     * Performs the division of two non-signed large integers.
498
     *
499
     * @return string[] The quotient and remainder.
500
     *
501
     * @pure
502
     */
503
    private function doDiv(string $a, string $b): array
504
    {
505
        $cmp = $this->doCmp($a, $b);
5,932✔
506

507
        if ($cmp === -1) {
5,932✔
508
            return ['0', $a];
631✔
509
        }
510

511
        $x = strlen($a);
5,885✔
512
        $y = strlen($b);
5,885✔
513

514
        // we now know that a >= b && x >= y
515

516
        $q = '0'; // quotient
5,885✔
517
        $r = $a; // remainder
5,885✔
518
        $z = $y; // focus length, always $y or $y+1
5,885✔
519

520
        /** @var numeric-string $b */
521
        $nb = $b * 1; // cast to number
5,885✔
522
        // performance optimization in cases where the remainder will never cause int overflow
523
        if (is_int(($nb - 1) * 10 + 9)) {
5,885✔
524
            $r = (int) substr($a, 0, $z - 1);
5,742✔
525

526
            for ($i = $z - 1; $i < $x; $i++) {
5,742✔
527
                $n = $r * 10 + (int) $a[$i];
5,742✔
528
                /** @var int $nb */
529
                $q .= intdiv($n, $nb);
5,742✔
530
                $r = $n % $nb;
5,742✔
531
            }
532

533
            return [ltrim($q, '0') ?: '0', (string) $r];
5,742✔
534
        }
535

536
        for (; ;) {
537
            $focus = substr($a, 0, $z);
4,121✔
538

539
            $cmp = $this->doCmp($focus, $b);
4,121✔
540

541
            if ($cmp === -1) {
4,121✔
542
                if ($z === $x) { // remainder < dividend
4,091✔
543
                    break;
3,950✔
544
                }
545

546
                $z++;
4,088✔
547
            }
548

549
            $zeros = str_repeat('0', $x - $z);
4,121✔
550

551
            $q = $this->add($q, '1' . $zeros);
4,121✔
552
            $a = $this->sub($a, $b . $zeros);
4,121✔
553

554
            $r = $a;
4,121✔
555

556
            if ($r === '0') { // remainder == 0
4,121✔
557
                break;
3,402✔
558
            }
559

560
            $x = strlen($a);
4,118✔
561

562
            if ($x < $y) { // remainder < dividend
4,118✔
563
                break;
3,913✔
564
            }
565

566
            $z = $y;
4,121✔
567
        }
568

569
        return [$q, $r];
4,121✔
570
    }
571

572
    /**
573
     * Compares two non-signed large numbers.
574
     *
575
     * @return -1|0|1
576
     *
577
     * @pure
578
     */
579
    private function doCmp(string $a, string $b): int
580
    {
581
        $x = strlen($a);
5,951✔
582
        $y = strlen($b);
5,951✔
583

584
        $cmp = $x <=> $y;
5,951✔
585

586
        if ($cmp !== 0) {
5,951✔
587
            return $cmp;
5,923✔
588
        }
589

590
        return strcmp($a, $b) <=> 0; // enforce -1|0|1
4,144✔
591
    }
592

593
    /**
594
     * Pads the left of one of the given numbers with zeros if necessary to make both numbers the same length.
595
     *
596
     * The numbers must only consist of digits, without leading minus sign.
597
     *
598
     * @return array{string, string, int}
599
     *
600
     * @pure
601
     */
602
    private function pad(string $a, string $b): array
603
    {
604
        $x = strlen($a);
5,114✔
605
        $y = strlen($b);
5,114✔
606

607
        if ($x > $y) {
5,114✔
608
            $b = str_repeat('0', $x - $y) . $b;
4,555✔
609

610
            return [$a, $b, $x];
4,555✔
611
        }
612

613
        if ($x < $y) {
4,936✔
614
            $a = str_repeat('0', $y - $x) . $a;
4,345✔
615

616
            return [$a, $b, $y];
4,345✔
617
        }
618

619
        return [$a, $b, $x];
4,544✔
620
    }
621
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc