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

brick / math / 21416478676

27 Jan 2026 10:20PM UTC coverage: 99.423% (+0.01%) from 99.412%
21416478676

push

github

BenMorel
Remove deprecated BigRational::simplified()

1207 of 1214 relevant lines covered (99.42%)

2597.78 hits per line

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

98.72
/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,811✔
62

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

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

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

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

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

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

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

86
    #[Override]
87
    public function sub(string $a, string $b): string
88
    {
89
        return $this->add($a, $this->neg($b));
4,715✔
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,043✔
100

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

174
            if (is_int($nb)) {
4,898✔
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,768✔
178
                $r = $na % $nb;
4,768✔
179

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

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

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

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

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

199
        return [$q, $r];
5,931✔
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
        // special case: the algorithm below fails with 0 power 0 mod 1 (returns 1 instead of 0)
234
        if ($base === '0' && $exp === '0' && $mod === '1') {
11✔
235
            return '0';
1✔
236
        }
237

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

243
        $x = $base;
9✔
244

245
        $res = '1';
9✔
246

247
        // numbers are positive, so we can use remainder instead of modulo
248
        $x = $this->divR($x, $mod);
9✔
249

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

255
            $exp = $this->divQ($exp, '2');
9✔
256
            $x = $this->divR($this->mul($x, $x), $mod);
9✔
257
        }
258

259
        return $res;
9✔
260
    }
261

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

272
        // initial approximation
273
        $x = str_repeat('9', intdiv(strlen($n), 2) ?: 1);
5,538✔
274

275
        $decreased = false;
5,538✔
276

277
        for (; ;) {
278
            $nx = $this->divQ($this->add($x, $this->divQ($n, $x)), '2');
5,538✔
279

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

284
            $decreased = $this->cmp($nx, $x) < 0;
5,528✔
285
            $x = $nx;
5,538✔
286
        }
287

288
        return $x;
5,538✔
289
    }
290

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

300
        $carry = 0;
4,949✔
301
        $result = '';
4,949✔
302

303
        for ($i = $length - $this->maxDigits; ; $i -= $this->maxDigits) {
4,949✔
304
            $blockLength = $this->maxDigits;
4,949✔
305

306
            if ($i < 0) {
4,949✔
307
                $blockLength += $i;
4,916✔
308
                $i = 0;
4,916✔
309
            }
310

311
            /** @var numeric-string $blockA */
312
            $blockA = substr($a, $i, $blockLength);
4,949✔
313

314
            /** @var numeric-string $blockB */
315
            $blockB = substr($b, $i, $blockLength);
4,949✔
316

317
            $sum = (string) ($blockA + $blockB + $carry);
4,949✔
318
            $sumLength = strlen($sum);
4,949✔
319

320
            if ($sumLength > $blockLength) {
4,949✔
321
                $sum = substr($sum, 1);
4,603✔
322
                $carry = 1;
4,603✔
323
            } else {
324
                if ($sumLength < $blockLength) {
4,949✔
325
                    $sum = str_repeat('0', $blockLength - $sumLength) . $sum;
4,534✔
326
                }
327
                $carry = 0;
4,949✔
328
            }
329

330
            $result = $sum . $result;
4,949✔
331

332
            if ($i === 0) {
4,949✔
333
                break;
4,949✔
334
            }
335
        }
336

337
        if ($carry === 1) {
4,949✔
338
            $result = '1' . $result;
3,112✔
339
        }
340

341
        return $result;
4,949✔
342
    }
343

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

355
        // Ensure that we always subtract to a positive result: biggest minus smallest.
356
        $cmp = $this->doCmp($a, $b);
4,159✔
357

358
        $invert = ($cmp === -1);
4,159✔
359

360
        if ($invert) {
4,159✔
361
            $c = $a;
40✔
362
            $a = $b;
40✔
363
            $b = $c;
40✔
364
        }
365

366
        [$a, $b, $length] = $this->pad($a, $b);
4,159✔
367

368
        $carry = 0;
4,159✔
369
        $result = '';
4,159✔
370

371
        $complement = 10 ** $this->maxDigits;
4,159✔
372

373
        for ($i = $length - $this->maxDigits; ; $i -= $this->maxDigits) {
4,159✔
374
            $blockLength = $this->maxDigits;
4,159✔
375

376
            if ($i < 0) {
4,159✔
377
                $blockLength += $i;
4,158✔
378
                $i = 0;
4,158✔
379
            }
380

381
            /** @var numeric-string $blockA */
382
            $blockA = substr($a, $i, $blockLength);
4,159✔
383

384
            /** @var numeric-string $blockB */
385
            $blockB = substr($b, $i, $blockLength);
4,159✔
386

387
            $sum = $blockA - $blockB - $carry;
4,159✔
388

389
            if ($sum < 0) {
4,159✔
390
                $sum += $complement;
4,111✔
391
                $carry = 1;
4,111✔
392
            } else {
393
                $carry = 0;
4,159✔
394
            }
395

396
            $sum = (string) $sum;
4,159✔
397
            $sumLength = strlen($sum);
4,159✔
398

399
            if ($sumLength < $blockLength) {
4,159✔
400
                $sum = str_repeat('0', $blockLength - $sumLength) . $sum;
4,125✔
401
            }
402

403
            $result = $sum . $result;
4,159✔
404

405
            if ($i === 0) {
4,159✔
406
                break;
4,159✔
407
            }
408
        }
409

410
        // Carry cannot be 1 when the loop ends, as a > b
411
        assert($carry === 0);
412

413
        $result = ltrim($result, '0');
4,159✔
414

415
        if ($invert) {
4,159✔
416
            $result = $this->neg($result);
40✔
417
        }
418

419
        return $result;
4,159✔
420
    }
421

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

432
        $maxDigits = intdiv($this->maxDigits, 2);
4,241✔
433
        $complement = 10 ** $maxDigits;
4,241✔
434

435
        $result = '0';
4,241✔
436

437
        for ($i = $x - $maxDigits; ; $i -= $maxDigits) {
4,241✔
438
            $blockALength = $maxDigits;
4,241✔
439

440
            if ($i < 0) {
4,241✔
441
                $blockALength += $i;
3,959✔
442
                $i = 0;
3,959✔
443
            }
444

445
            $blockA = (int) substr($a, $i, $blockALength);
4,241✔
446

447
            $line = '';
4,241✔
448
            $carry = 0;
4,241✔
449

450
            for ($j = $y - $maxDigits; ; $j -= $maxDigits) {
4,241✔
451
                $blockBLength = $maxDigits;
4,241✔
452

453
                if ($j < 0) {
4,241✔
454
                    $blockBLength += $j;
3,987✔
455
                    $j = 0;
3,987✔
456
                }
457

458
                $blockB = (int) substr($b, $j, $blockBLength);
4,241✔
459

460
                $mul = $blockA * $blockB + $carry;
4,241✔
461
                $value = $mul % $complement;
4,241✔
462
                $carry = ($mul - $value) / $complement;
4,241✔
463

464
                $value = (string) $value;
4,241✔
465
                $value = str_pad($value, $maxDigits, '0', STR_PAD_LEFT);
4,241✔
466

467
                $line = $value . $line;
4,241✔
468

469
                if ($j === 0) {
4,241✔
470
                    break;
4,241✔
471
                }
472
            }
473

474
            if ($carry !== 0) {
4,241✔
475
                $line = $carry . $line;
4,168✔
476
            }
477

478
            $line = ltrim($line, '0');
4,241✔
479

480
            if ($line !== '') {
4,241✔
481
                $line .= str_repeat('0', $x - $blockALength - $i);
4,241✔
482
                $result = $this->add($result, $line);
4,241✔
483
            }
484

485
            if ($i === 0) {
4,241✔
486
                break;
4,241✔
487
            }
488
        }
489

490
        return $result;
4,241✔
491
    }
492

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

504
        if ($cmp === -1) {
5,931✔
505
            return ['0', $a];
631✔
506
        }
507

508
        $x = strlen($a);
5,883✔
509
        $y = strlen($b);
5,883✔
510

511
        // we now know that a >= b && x >= y
512

513
        $q = '0'; // quotient
5,883✔
514
        $r = $a; // remainder
5,883✔
515
        $z = $y; // focus length, always $y or $y+1
5,883✔
516

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

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

530
            return [ltrim($q, '0') ?: '0', (string) $r];
5,740✔
531
        }
532

533
        for (; ;) {
534
            $focus = substr($a, 0, $z);
4,120✔
535

536
            $cmp = $this->doCmp($focus, $b);
4,120✔
537

538
            if ($cmp === -1) {
4,120✔
539
                if ($z === $x) { // remainder < dividend
4,093✔
540
                    break;
3,952✔
541
                }
542

543
                $z++;
4,089✔
544
            }
545

546
            $zeros = str_repeat('0', $x - $z);
4,120✔
547

548
            $q = $this->add($q, '1' . $zeros);
4,120✔
549
            $a = $this->sub($a, $b . $zeros);
4,120✔
550

551
            $r = $a;
4,120✔
552

553
            if ($r === '0') { // remainder == 0
4,120✔
554
                break;
3,402✔
555
            }
556

557
            $x = strlen($a);
4,117✔
558

559
            if ($x < $y) { // remainder < dividend
4,117✔
560
                break;
3,910✔
561
            }
562

563
            $z = $y;
4,120✔
564
        }
565

566
        return [$q, $r];
4,120✔
567
    }
568

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

581
        $cmp = $x <=> $y;
5,951✔
582

583
        if ($cmp !== 0) {
5,951✔
584
            return $cmp;
5,921✔
585
        }
586

587
        return strcmp($a, $b) <=> 0; // enforce -1|0|1
4,145✔
588
    }
589

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

604
        if ($x > $y) {
5,105✔
605
            $b = str_repeat('0', $x - $y) . $b;
4,553✔
606

607
            return [$a, $b, $x];
4,553✔
608
        }
609

610
        if ($x < $y) {
4,927✔
611
            $a = str_repeat('0', $y - $x) . $a;
4,332✔
612

613
            return [$a, $b, $y];
4,332✔
614
        }
615

616
        return [$a, $b, $x];
4,545✔
617
    }
618
}
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