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

brick / math / 21038865865

15 Jan 2026 04:37PM UTC coverage: 79.746% (-18.9%) from 98.597%
21038865865

push

github

BenMorel
Revert "Claude performance improvements"

This reverts commit 3b60a23df.

0 of 41 new or added lines in 1 file covered. (0.0%)

5 existing lines in 1 file now uncovered.

941 of 1180 relevant lines covered (79.75%)

607.9 hits per line

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

0.0
/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;
×
62

63
        if (is_int($result)) {
×
64
            return (string) $result;
×
65
        }
66

67
        if ($a === '0') {
×
68
            return $b;
×
69
        }
70

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

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

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

79
        if ($aNeg) {
×
80
            $result = $this->neg($result);
×
81
        }
82

83
        return $result;
×
84
    }
85

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

101
        if (is_int($result)) {
×
102
            return (string) $result;
×
103
        }
104

105
        if ($a === '0' || $b === '0') {
×
106
            return '0';
×
107
        }
108

109
        if ($a === '1') {
×
110
            return $b;
×
111
        }
112

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

117
        if ($a === '-1') {
×
118
            return $this->neg($b);
×
119
        }
120

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

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

127
        $result = $this->doMul($aDig, $bDig);
×
128

129
        if ($aNeg !== $bNeg) {
×
130
            $result = $this->neg($result);
×
131
        }
132

133
        return $result;
×
134
    }
135

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

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

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

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

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

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

167
        /** @var numeric-string $a */
168
        $na = $a * 1; // cast to number
×
169

170
        if (is_int($na)) {
×
171
            /** @var numeric-string $b */
172
            $nb = $b * 1;
×
173

174
            if (is_int($nb)) {
×
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);
×
178
                $r = $na % $nb;
×
179

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

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

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

191
        if ($aNeg !== $bNeg) {
×
192
            $q = $this->neg($q);
×
193
        }
194

195
        if ($aNeg) {
×
196
            $r = $this->neg($r);
×
197
        }
198

199
        return [$q, $r];
×
200
    }
201

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

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

213
        $odd = $e % 2;
×
214
        $e -= $odd;
×
215

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

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

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

224
        return $result;
×
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)
NEW
234
        if ($base === '0' && $exp === '0' && $mod === '1') {
×
UNCOV
235
            return '0';
×
236
        }
237

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

243
        $x = $base;
×
244

245
        $res = '1';
×
246

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

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

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

259
        return $res;
×
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') {
×
269
            return '0';
×
270
        }
271

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

275
        $decreased = false;
×
276

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

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

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

288
        return $x;
×
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);
×
299

300
        $carry = 0;
×
NEW
301
        $result = '';
×
302

303
        for ($i = $length - $this->maxDigits; ; $i -= $this->maxDigits) {
×
304
            $blockLength = $this->maxDigits;
×
305

306
            if ($i < 0) {
×
307
                $blockLength += $i;
×
308
                $i = 0;
×
309
            }
310

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

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

317
            $sum = (string) ($blockA + $blockB + $carry);
×
318
            $sumLength = strlen($sum);
×
319

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

NEW
330
            $result = $sum . $result;
×
331

332
            if ($i === 0) {
×
333
                break;
×
334
            }
335
        }
336

337
        if ($carry === 1) {
×
UNCOV
338
            $result = '1' . $result;
×
339
        }
340

341
        return $result;
×
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) {
×
352
            return '0';
×
353
        }
354

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

358
        $invert = ($cmp === -1);
×
359

360
        if ($invert) {
×
361
            $c = $a;
×
362
            $a = $b;
×
363
            $b = $c;
×
364
        }
365

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

368
        $carry = 0;
×
NEW
369
        $result = '';
×
370

371
        $complement = 10 ** $this->maxDigits;
×
372

373
        for ($i = $length - $this->maxDigits; ; $i -= $this->maxDigits) {
×
374
            $blockLength = $this->maxDigits;
×
375

376
            if ($i < 0) {
×
377
                $blockLength += $i;
×
378
                $i = 0;
×
379
            }
380

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

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

387
            $sum = $blockA - $blockB - $carry;
×
388

389
            if ($sum < 0) {
×
390
                $sum += $complement;
×
391
                $carry = 1;
×
392
            } else {
393
                $carry = 0;
×
394
            }
395

396
            $sum = (string) $sum;
×
397
            $sumLength = strlen($sum);
×
398

399
            if ($sumLength < $blockLength) {
×
NEW
400
                $sum = str_repeat('0', $blockLength - $sumLength) . $sum;
×
401
            }
402

NEW
403
            $result = $sum . $result;
×
404

405
            if ($i === 0) {
×
406
                break;
×
407
            }
408
        }
409

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

NEW
413
        $result = ltrim($result, '0');
×
414

415
        if ($invert) {
×
416
            $result = $this->neg($result);
×
417
        }
418

419
        return $result;
×
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);
×
430
        $y = strlen($b);
×
431

UNCOV
432
        $maxDigits = intdiv($this->maxDigits, 2);
×
UNCOV
433
        $complement = 10 ** $maxDigits;
×
434

435
        $result = '0';
×
436

437
        for ($i = $x - $maxDigits; ; $i -= $maxDigits) {
×
438
            $blockALength = $maxDigits;
×
439

440
            if ($i < 0) {
×
441
                $blockALength += $i;
×
442
                $i = 0;
×
443
            }
444

445
            $blockA = (int) substr($a, $i, $blockALength);
×
446

NEW
447
            $line = '';
×
448
            $carry = 0;
×
449

450
            for ($j = $y - $maxDigits; ; $j -= $maxDigits) {
×
451
                $blockBLength = $maxDigits;
×
452

453
                if ($j < 0) {
×
454
                    $blockBLength += $j;
×
455
                    $j = 0;
×
456
                }
457

458
                $blockB = (int) substr($b, $j, $blockBLength);
×
459

460
                $mul = $blockA * $blockB + $carry;
×
461
                $value = $mul % $complement;
×
NEW
462
                $carry = ($mul - $value) / $complement;
×
463

NEW
464
                $value = (string) $value;
×
NEW
465
                $value = str_pad($value, $maxDigits, '0', STR_PAD_LEFT);
×
466

NEW
467
                $line = $value . $line;
×
468

469
                if ($j === 0) {
×
470
                    break;
×
471
                }
472
            }
473

474
            if ($carry !== 0) {
×
UNCOV
475
                $line = $carry . $line;
×
476
            }
477

478
            $line = ltrim($line, '0');
×
479

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

485
            if ($i === 0) {
×
486
                break;
×
487
            }
488
        }
489

490
        return $result;
×
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);
×
503

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

508
        $x = strlen($a);
×
509
        $y = strlen($b);
×
510

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

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

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

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

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

533
        for (; ;) {
NEW
534
            $focus = substr($a, 0, $z);
×
535

NEW
536
            $cmp = $this->doCmp($focus, $b);
×
537

NEW
538
            if ($cmp === -1) {
×
NEW
539
                if ($z === $x) { // remainder < dividend
×
NEW
540
                    break;
×
541
                }
542

NEW
543
                $z++;
×
544
            }
545

NEW
546
            $zeros = str_repeat('0', $x - $z);
×
547

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

NEW
551
            $r = $a;
×
552

NEW
553
            if ($r === '0') { // remainder == 0
×
NEW
554
                break;
×
555
            }
556

NEW
557
            $x = strlen($a);
×
558

NEW
559
            if ($x < $y) { // remainder < dividend
×
NEW
560
                break;
×
561
            }
562

NEW
563
            $z = $y;
×
564
        }
565

NEW
566
        return [$q, $r];
×
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);
×
579
        $y = strlen($b);
×
580

581
        $cmp = $x <=> $y;
×
582

583
        if ($cmp !== 0) {
×
584
            return $cmp;
×
585
        }
586

587
        return strcmp($a, $b) <=> 0; // enforce -1|0|1
×
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);
×
602
        $y = strlen($b);
×
603

604
        if ($x > $y) {
×
605
            $b = str_repeat('0', $x - $y) . $b;
×
606

607
            return [$a, $b, $x];
×
608
        }
609

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

613
            return [$a, $b, $y];
×
614
        }
615

616
        return [$a, $b, $x];
×
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