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

brick / math / 21640062619

03 Feb 2026 05:11PM UTC coverage: 99.327% (+0.02%) from 99.308%
21640062619

push

github

BenMorel
Prepare for upcoming breaking change in sqrt()

12 of 12 new or added lines in 2 files covered. (100.0%)

3 existing lines in 1 file now uncovered.

1328 of 1337 relevant lines covered (99.33%)

2388.76 hits per line

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

99.09
/src/BigInteger.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Brick\Math;
6

7
use Brick\Math\Exception\DivisionByZeroException;
8
use Brick\Math\Exception\IntegerOverflowException;
9
use Brick\Math\Exception\MathException;
10
use Brick\Math\Exception\NegativeNumberException;
11
use Brick\Math\Exception\NumberFormatException;
12
use Brick\Math\Exception\RoundingNecessaryException;
13
use Brick\Math\Internal\Calculator;
14
use Brick\Math\Internal\CalculatorRegistry;
15
use InvalidArgumentException;
16
use LogicException;
17
use Override;
18

19
use function assert;
20
use function bin2hex;
21
use function chr;
22
use function count_chars;
23
use function filter_var;
24
use function func_num_args;
25
use function hex2bin;
26
use function in_array;
27
use function intdiv;
28
use function ltrim;
29
use function ord;
30
use function preg_match;
31
use function preg_quote;
32
use function random_bytes;
33
use function sprintf;
34
use function str_repeat;
35
use function strlen;
36
use function strtolower;
37
use function substr;
38
use function trigger_error;
39

40
use const E_USER_DEPRECATED;
41
use const FILTER_VALIDATE_INT;
42

43
/**
44
 * An arbitrarily large integer number.
45
 *
46
 * This class is immutable.
47
 */
48
final readonly class BigInteger extends BigNumber
49
{
50
    /**
51
     * The value, as a string of digits with optional leading minus sign.
52
     *
53
     * No leading zeros must be present.
54
     * No leading minus sign must be present if the number is zero.
55
     */
56
    private string $value;
57

58
    /**
59
     * Protected constructor. Use a factory method to obtain an instance.
60
     *
61
     * @param string $value A string of digits, with optional leading minus sign.
62
     *
63
     * @pure
64
     */
65
    protected function __construct(string $value)
66
    {
67
        $this->value = $value;
31,418✔
68
    }
69

70
    /**
71
     * Creates a number from a string in a given base.
72
     *
73
     * The string can optionally be prefixed with the `+` or `-` sign.
74
     *
75
     * Bases greater than 36 are not supported by this method, as there is no clear consensus on which of the lowercase
76
     * or uppercase characters should come first. Instead, this method accepts any base up to 36, and does not
77
     * differentiate lowercase and uppercase characters, which are considered equal.
78
     *
79
     * For bases greater than 36, and/or custom alphabets, use the fromArbitraryBase() method.
80
     *
81
     * @param string $number The number to convert, in the given base.
82
     * @param int    $base   The base of the number, between 2 and 36.
83
     *
84
     * @throws NumberFormatException    If the number is empty, or contains invalid chars for the given base.
85
     * @throws InvalidArgumentException If the base is out of range.
86
     *
87
     * @pure
88
     */
89
    public static function fromBase(string $number, int $base): BigInteger
90
    {
91
        if ($number === '') {
2,093✔
92
            throw new NumberFormatException('The number must not be empty.');
3✔
93
        }
94

95
        if ($base < 2 || $base > 36) {
2,090✔
96
            throw new InvalidArgumentException(sprintf('Base %d is not in range 2 to 36.', $base));
15✔
97
        }
98

99
        if ($number[0] === '-') {
2,075✔
100
            $sign = '-';
27✔
101
            $number = substr($number, 1);
27✔
102
        } elseif ($number[0] === '+') {
2,048✔
103
            $sign = '';
27✔
104
            $number = substr($number, 1);
27✔
105
        } else {
106
            $sign = '';
2,021✔
107
        }
108

109
        if ($number === '') {
2,075✔
110
            throw new NumberFormatException('The number must not be empty.');
6✔
111
        }
112

113
        $number = ltrim($number, '0');
2,069✔
114

115
        if ($number === '') {
2,069✔
116
            // The result will be the same in any base, avoid further calculation.
117
            return BigInteger::zero();
84✔
118
        }
119

120
        if ($number === '1') {
1,988✔
121
            // The result will be the same in any base, avoid further calculation.
122
            return new BigInteger($sign . '1');
75✔
123
        }
124

125
        $pattern = '/[^' . substr(Calculator::ALPHABET, 0, $base) . ']/';
1,916✔
126

127
        if (preg_match($pattern, strtolower($number), $matches) === 1) {
1,916✔
128
            throw new NumberFormatException(sprintf('"%s" is not a valid character in base %d.', $matches[0], $base));
111✔
129
        }
130

131
        if ($base === 10) {
1,805✔
132
            // The number is usable as is, avoid further calculation.
133
            return new BigInteger($sign . $number);
24✔
134
        }
135

136
        $result = CalculatorRegistry::get()->fromBase($number, $base);
1,781✔
137

138
        return new BigInteger($sign . $result);
1,781✔
139
    }
140

141
    /**
142
     * Parses a string containing an integer in an arbitrary base, using a custom alphabet.
143
     *
144
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers.
145
     *
146
     * @param string $number   The number to parse.
147
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
148
     *
149
     * @throws NumberFormatException    If the given number is empty or contains invalid chars for the given alphabet.
150
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars, or contains duplicates.
151
     *
152
     * @pure
153
     */
154
    public static function fromArbitraryBase(string $number, string $alphabet): BigInteger
155
    {
156
        if ($number === '') {
423✔
157
            throw new NumberFormatException('The number must not be empty.');
3✔
158
        }
159

160
        $base = strlen($alphabet);
420✔
161

162
        if ($base < 2) {
420✔
163
            throw new InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
164
        }
165

166
        if (strlen(count_chars($alphabet, 3)) !== $base) {
414✔
167
            throw new InvalidArgumentException('The alphabet must not contain duplicate chars.');
9✔
168
        }
169

170
        $pattern = '/[^' . preg_quote($alphabet, '/') . ']/';
405✔
171

172
        if (preg_match($pattern, $number, $matches) === 1) {
405✔
173
            throw NumberFormatException::charNotInAlphabet($matches[0]);
27✔
174
        }
175

176
        $number = CalculatorRegistry::get()->fromArbitraryBase($number, $alphabet, $base);
378✔
177

178
        return new BigInteger($number);
378✔
179
    }
180

181
    /**
182
     * Translates a string of bytes containing the binary representation of a BigInteger into a BigInteger.
183
     *
184
     * The input string is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element.
185
     *
186
     * If `$signed` is true, the input is assumed to be in two's-complement representation, and the leading bit is
187
     * interpreted as a sign bit. If `$signed` is false, the input is interpreted as an unsigned number, and the
188
     * resulting BigInteger will always be positive or zero.
189
     *
190
     * This method can be used to retrieve a number exported by `toBytes()`, as long as the `$signed` flags match.
191
     *
192
     * @param string $value  The byte string.
193
     * @param bool   $signed Whether to interpret as a signed number in two's-complement representation with a leading
194
     *                       sign bit.
195
     *
196
     * @throws NumberFormatException If the string is empty.
197
     *
198
     * @pure
199
     */
200
    public static function fromBytes(string $value, bool $signed = true): BigInteger
201
    {
202
        if ($value === '') {
1,224✔
203
            throw new NumberFormatException('The byte string must not be empty.');
3✔
204
        }
205

206
        $twosComplement = false;
1,221✔
207

208
        if ($signed) {
1,221✔
209
            $x = ord($value[0]);
984✔
210

211
            if (($twosComplement = ($x >= 0x80))) {
984✔
212
                $value = ~$value;
906✔
213
            }
214
        }
215

216
        $number = self::fromBase(bin2hex($value), 16);
1,221✔
217

218
        if ($twosComplement) {
1,221✔
219
            return $number->plus(1)->negated();
906✔
220
        }
221

222
        return $number;
315✔
223
    }
224

225
    /**
226
     * Generates a pseudo-random number in the range 0 to 2^numBits - 1.
227
     *
228
     * Using the default random bytes generator, this method is suitable for cryptographic use.
229
     *
230
     * @param int                          $numBits              The number of bits.
231
     * @param (callable(int): string)|null $randomBytesGenerator A function that accepts a number of bytes, and returns
232
     *                                                           a string of random bytes of the given length. Defaults
233
     *                                                           to the `random_bytes()` function.
234
     *
235
     * @throws InvalidArgumentException If $numBits is negative.
236
     */
237
    public static function randomBits(int $numBits, ?callable $randomBytesGenerator = null): BigInteger
238
    {
239
        if ($numBits < 0) {
165✔
240
            throw new InvalidArgumentException('The number of bits must not be negative.');
3✔
241
        }
242

243
        if ($numBits === 0) {
162✔
244
            return BigInteger::zero();
3✔
245
        }
246

247
        if ($randomBytesGenerator === null) {
159✔
UNCOV
248
            $randomBytesGenerator = random_bytes(...);
×
249
        }
250

251
        /** @var int<1, max> $byteLength */
252
        $byteLength = intdiv($numBits - 1, 8) + 1;
159✔
253

254
        $extraBits = ($byteLength * 8 - $numBits);
159✔
255
        $bitmask = chr(0xFF >> $extraBits);
159✔
256

257
        $randomBytes = $randomBytesGenerator($byteLength);
159✔
258
        $randomBytes[0] = $randomBytes[0] & $bitmask;
159✔
259

260
        return self::fromBytes($randomBytes, false);
159✔
261
    }
262

263
    /**
264
     * Generates a pseudo-random number between `$min` and `$max`.
265
     *
266
     * Using the default random bytes generator, this method is suitable for cryptographic use.
267
     *
268
     * @param BigNumber|int|float|string   $min                  The lower bound. Must be convertible to a BigInteger.
269
     * @param BigNumber|int|float|string   $max                  The upper bound. Must be convertible to a BigInteger.
270
     * @param (callable(int): string)|null $randomBytesGenerator A function that accepts a number of bytes, and returns
271
     *                                                           a string of random bytes of the given length. Defaults
272
     *                                                           to the `random_bytes()` function.
273
     *
274
     * @throws MathException If one of the parameters cannot be converted to a BigInteger,
275
     *                       or `$min` is greater than `$max`.
276
     */
277
    public static function randomRange(
278
        BigNumber|int|float|string $min,
279
        BigNumber|int|float|string $max,
280
        ?callable $randomBytesGenerator = null,
281
    ): BigInteger {
282
        $min = BigInteger::of($min);
84✔
283
        $max = BigInteger::of($max);
84✔
284

285
        if ($min->isGreaterThan($max)) {
84✔
286
            throw new MathException('$min must be less than or equal to $max.');
3✔
287
        }
288

289
        if ($min->isEqualTo($max)) {
81✔
290
            return $min;
3✔
291
        }
292

293
        $diff = $max->minus($min);
78✔
294
        $bitLength = $diff->getBitLength();
78✔
295

296
        // try until the number is in range (50% to 100% chance of success)
297
        do {
298
            $randomNumber = self::randomBits($bitLength, $randomBytesGenerator);
78✔
299
        } while ($randomNumber->isGreaterThan($diff));
78✔
300

301
        return $randomNumber->plus($min);
78✔
302
    }
303

304
    /**
305
     * Returns a BigInteger representing zero.
306
     *
307
     * @pure
308
     */
309
    public static function zero(): BigInteger
310
    {
311
        /** @var BigInteger|null $zero */
312
        static $zero;
219✔
313

314
        if ($zero === null) {
219✔
UNCOV
315
            $zero = new BigInteger('0');
×
316
        }
317

318
        return $zero;
219✔
319
    }
320

321
    /**
322
     * Returns a BigInteger representing one.
323
     *
324
     * @pure
325
     */
326
    public static function one(): BigInteger
327
    {
328
        /** @var BigInteger|null $one */
329
        static $one;
528✔
330

331
        if ($one === null) {
528✔
UNCOV
332
            $one = new BigInteger('1');
×
333
        }
334

335
        return $one;
528✔
336
    }
337

338
    /**
339
     * Returns a BigInteger representing ten.
340
     *
341
     * @pure
342
     */
343
    public static function ten(): BigInteger
344
    {
345
        /** @var BigInteger|null $ten */
346
        static $ten;
6✔
347

348
        if ($ten === null) {
6✔
349
            $ten = new BigInteger('10');
3✔
350
        }
351

352
        return $ten;
6✔
353
    }
354

355
    /**
356
     * @param BigNumber|int|float|string $a    The first number. Must be convertible to a BigInteger.
357
     * @param BigNumber|int|float|string ...$n The subsequent numbers. Must be convertible to BigInteger.
358
     *
359
     * @pure
360
     */
361
    public static function gcdAll(BigNumber|int|float|string $a, BigNumber|int|float|string ...$n): BigInteger
362
    {
363
        $result = BigInteger::of($a)->abs();
1,587✔
364

365
        foreach ($n as $next) {
1,587✔
366
            $result = $result->gcd(BigInteger::of($next));
1,560✔
367

368
            if ($result->isEqualTo(1)) {
1,560✔
369
                return $result;
345✔
370
            }
371
        }
372

373
        return $result;
1,242✔
374
    }
375

376
    /**
377
     * @param BigNumber|int|float|string $a    The first number. Must be convertible to a BigInteger.
378
     * @param BigNumber|int|float|string ...$n The subsequent numbers. Must be convertible to BigInteger.
379
     *
380
     * @pure
381
     */
382
    public static function lcmAll(BigNumber|int|float|string $a, BigNumber|int|float|string ...$n): BigInteger
383
    {
384
        $result = BigInteger::of($a)->abs();
324✔
385

386
        foreach ($n as $next) {
324✔
387
            $result = $result->lcm(BigInteger::of($next));
297✔
388

389
            if ($result->isZero()) {
297✔
390
                return $result;
51✔
391
            }
392
        }
393

394
        return $result;
273✔
395
    }
396

397
    /**
398
     * @deprecated Use gcdAll() instead.
399
     *
400
     * @param BigNumber|int|float|string $a    The first number. Must be convertible to a BigInteger.
401
     * @param BigNumber|int|float|string ...$n The subsequent numbers. Must be convertible to BigInteger.
402
     */
403
    public static function gcdMultiple(BigNumber|int|float|string $a, BigNumber|int|float|string ...$n): BigInteger
404
    {
405
        trigger_error(
1,587✔
406
            'BigInteger::gcdMultiple() is deprecated and will be removed in version 0.15. Use gcdAll() instead.',
1,587✔
407
            E_USER_DEPRECATED,
1,587✔
408
        );
1,587✔
409

410
        return self::gcdAll($a, ...$n);
1,587✔
411
    }
412

413
    /**
414
     * Returns the sum of this number and the given one.
415
     *
416
     * @param BigNumber|int|float|string $that The number to add. Must be convertible to a BigInteger.
417
     *
418
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
419
     *
420
     * @pure
421
     */
422
    public function plus(BigNumber|int|float|string $that): BigInteger
423
    {
424
        $that = BigInteger::of($that);
1,629✔
425

426
        if ($that->value === '0') {
1,629✔
427
            return $this;
30✔
428
        }
429

430
        if ($this->value === '0') {
1,599✔
431
            return $that;
72✔
432
        }
433

434
        $value = CalculatorRegistry::get()->add($this->value, $that->value);
1,548✔
435

436
        return new BigInteger($value);
1,548✔
437
    }
438

439
    /**
440
     * Returns the difference of this number and the given one.
441
     *
442
     * @param BigNumber|int|float|string $that The number to subtract. Must be convertible to a BigInteger.
443
     *
444
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
445
     *
446
     * @pure
447
     */
448
    public function minus(BigNumber|int|float|string $that): BigInteger
449
    {
450
        $that = BigInteger::of($that);
990✔
451

452
        if ($that->value === '0') {
990✔
453
            return $this;
30✔
454
        }
455

456
        $value = CalculatorRegistry::get()->sub($this->value, $that->value);
969✔
457

458
        return new BigInteger($value);
969✔
459
    }
460

461
    /**
462
     * Returns the product of this number and the given one.
463
     *
464
     * @param BigNumber|int|float|string $that The multiplier. Must be convertible to a BigInteger.
465
     *
466
     * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigInteger.
467
     *
468
     * @pure
469
     */
470
    public function multipliedBy(BigNumber|int|float|string $that): BigInteger
471
    {
472
        $that = BigInteger::of($that);
1,338✔
473

474
        if ($that->value === '1') {
1,338✔
475
            return $this;
345✔
476
        }
477

478
        if ($this->value === '1') {
1,314✔
479
            return $that;
378✔
480
        }
481

482
        $value = CalculatorRegistry::get()->mul($this->value, $that->value);
1,206✔
483

484
        return new BigInteger($value);
1,206✔
485
    }
486

487
    /**
488
     * Returns the result of the division of this number by the given one.
489
     *
490
     * @param BigNumber|int|float|string $that         The divisor. Must be convertible to a BigInteger.
491
     * @param RoundingMode               $roundingMode An optional rounding mode, defaults to Unnecessary.
492
     *
493
     * @throws MathException If the divisor is not a valid number, is not convertible to a BigInteger, is zero,
494
     *                       or RoundingMode::Unnecessary is used and the remainder is not zero.
495
     *
496
     * @pure
497
     */
498
    public function dividedBy(BigNumber|int|float|string $that, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
499
    {
500
        $that = BigInteger::of($that);
1,980✔
501

502
        if ($that->value === '1') {
1,971✔
503
            return $this;
3✔
504
        }
505

506
        if ($that->value === '0') {
1,968✔
507
            throw DivisionByZeroException::divisionByZero();
6✔
508
        }
509

510
        $result = CalculatorRegistry::get()->divRound($this->value, $that->value, $roundingMode);
1,962✔
511

512
        return new BigInteger($result);
1,869✔
513
    }
514

515
    /**
516
     * Limits (clamps) this number between the given minimum and maximum values.
517
     *
518
     * If the number is lower than $min, returns a copy of $min.
519
     * If the number is greater than $max, returns a copy of $max.
520
     * Otherwise, returns this number unchanged.
521
     *
522
     * @param BigNumber|int|float|string $min The minimum. Must be convertible to a BigInteger.
523
     * @param BigNumber|int|float|string $max The maximum. Must be convertible to a BigInteger.
524
     *
525
     * @throws MathException            If min/max are not convertible to a BigInteger.
526
     * @throws InvalidArgumentException If min is greater than max.
527
     *
528
     * @pure
529
     */
530
    public function clamp(BigNumber|int|float|string $min, BigNumber|int|float|string $max): BigInteger
531
    {
532
        $min = BigInteger::of($min);
33✔
533
        $max = BigInteger::of($max);
33✔
534

535
        if ($min->isGreaterThan($max)) {
33✔
536
            throw new InvalidArgumentException('Minimum value must be less than or equal to maximum value.');
3✔
537
        }
538

539
        if ($this->isLessThan($min)) {
30✔
540
            return $min;
9✔
541
        } elseif ($this->isGreaterThan($max)) {
21✔
542
            return $max;
3✔
543
        }
544

545
        return $this;
18✔
546
    }
547

548
    /**
549
     * Returns this number exponentiated to the given value.
550
     *
551
     * @throws InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
552
     *
553
     * @pure
554
     */
555
    public function power(int $exponent): BigInteger
556
    {
557
        if ($exponent === 0) {
1,851✔
558
            return BigInteger::one();
27✔
559
        }
560

561
        if ($exponent === 1) {
1,824✔
562
            return $this;
204✔
563
        }
564

565
        if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
1,620✔
566
            throw new InvalidArgumentException(sprintf(
6✔
567
                'The exponent %d is not in the range 0 to %d.',
6✔
568
                $exponent,
6✔
569
                Calculator::MAX_POWER,
6✔
570
            ));
6✔
571
        }
572

573
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,614✔
574
    }
575

576
    /**
577
     * Returns the quotient of the division of this number by the given one.
578
     *
579
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
580
     *
581
     * @throws DivisionByZeroException If the divisor is zero.
582
     *
583
     * @pure
584
     */
585
    public function quotient(BigNumber|int|float|string $that): BigInteger
586
    {
587
        $that = BigInteger::of($that);
1,095✔
588

589
        if ($that->value === '1') {
1,095✔
590
            return $this;
75✔
591
        }
592

593
        if ($that->value === '0') {
1,020✔
594
            throw DivisionByZeroException::divisionByZero();
3✔
595
        }
596

597
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
1,017✔
598

599
        return new BigInteger($quotient);
1,017✔
600
    }
601

602
    /**
603
     * Returns the remainder of the division of this number by the given one.
604
     *
605
     * The remainder, when non-zero, has the same sign as the dividend.
606
     *
607
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
608
     *
609
     * @throws DivisionByZeroException If the divisor is zero.
610
     *
611
     * @pure
612
     */
613
    public function remainder(BigNumber|int|float|string $that): BigInteger
614
    {
615
        $that = BigInteger::of($that);
285✔
616

617
        if ($that->value === '1') {
285✔
618
            return BigInteger::zero();
21✔
619
        }
620

621
        if ($that->value === '0') {
264✔
622
            throw DivisionByZeroException::divisionByZero();
3✔
623
        }
624

625
        $remainder = CalculatorRegistry::get()->divR($this->value, $that->value);
261✔
626

627
        return new BigInteger($remainder);
261✔
628
    }
629

630
    /**
631
     * Returns the quotient and remainder of the division of this number by the given one.
632
     *
633
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
634
     *
635
     * @return array{BigInteger, BigInteger} An array containing the quotient and the remainder.
636
     *
637
     * @throws DivisionByZeroException If the divisor is zero.
638
     *
639
     * @pure
640
     */
641
    public function quotientAndRemainder(BigNumber|int|float|string $that): array
642
    {
643
        $that = BigInteger::of($that);
159✔
644

645
        if ($that->value === '0') {
159✔
646
            throw DivisionByZeroException::divisionByZero();
3✔
647
        }
648

649
        [$quotient, $remainder] = CalculatorRegistry::get()->divQR($this->value, $that->value);
156✔
650

651
        return [
156✔
652
            new BigInteger($quotient),
156✔
653
            new BigInteger($remainder),
156✔
654
        ];
156✔
655
    }
656

657
    /**
658
     * Returns the modulo of this number and the given one.
659
     *
660
     * The modulo operation yields the same result as the remainder operation when both operands are of the same sign,
661
     * and may differ when signs are different.
662
     *
663
     * The result of the modulo operation, when non-zero, has the same sign as the divisor.
664
     *
665
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
666
     *
667
     * @throws DivisionByZeroException If the divisor is zero.
668
     *
669
     * @pure
670
     */
671
    public function mod(BigNumber|int|float|string $that): BigInteger
672
    {
673
        $that = BigInteger::of($that);
195✔
674

675
        if ($that->isZero()) {
195✔
676
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
677
        }
678

679
        if ($that->isNegative()) {
192✔
680
            // @phpstan-ignore-next-line
681
            trigger_error(
93✔
682
                'Passing a negative modulus to BigInteger::mod() is deprecated and will throw a NegativeNumberException in 0.15.',
93✔
683
                E_USER_DEPRECATED,
93✔
684
            );
93✔
685
        }
686

687
        $value = CalculatorRegistry::get()->mod($this->value, $that->value);
192✔
688

689
        return new BigInteger($value);
192✔
690
    }
691

692
    /**
693
     * Returns the modular multiplicative inverse of this BigInteger modulo $m.
694
     *
695
     * @param BigNumber|int|float|string $m The modulus. Must be convertible to a BigInteger.
696
     *
697
     * @throws DivisionByZeroException If $m is zero.
698
     * @throws NegativeNumberException If $m is negative.
699
     * @throws MathException           If this BigInteger has no multiplicative inverse mod m (that is, this BigInteger
700
     *                                 is not relatively prime to m).
701
     *
702
     * @pure
703
     */
704
    public function modInverse(BigNumber|int|float|string $m): BigInteger
705
    {
706
        $m = BigInteger::of($m);
75✔
707

708
        if ($m->value === '0') {
75✔
709
            throw DivisionByZeroException::modulusMustNotBeZero();
6✔
710
        }
711

712
        if ($m->isNegative()) {
69✔
713
            throw new NegativeNumberException('Modulus must not be negative.');
3✔
714
        }
715

716
        if ($m->value === '1') {
66✔
717
            return BigInteger::zero();
3✔
718
        }
719

720
        $value = CalculatorRegistry::get()->modInverse($this->value, $m->value);
63✔
721

722
        if ($value === null) {
63✔
723
            throw new MathException('Unable to compute the modInverse for the given modulus.');
15✔
724
        }
725

726
        return new BigInteger($value);
48✔
727
    }
728

729
    /**
730
     * Returns this number raised into power with modulo.
731
     *
732
     * This operation requires a non-negative exponent and a strictly positive modulus.
733
     *
734
     * @param BigNumber|int|float|string $exp The exponent. Must be positive or zero.
735
     * @param BigNumber|int|float|string $mod The modulus. Must be strictly positive.
736
     *
737
     * @throws NegativeNumberException If the exponent or modulus is negative.
738
     * @throws DivisionByZeroException If the modulus is zero.
739
     *
740
     * @pure
741
     */
742
    public function modPow(BigNumber|int|float|string $exp, BigNumber|int|float|string $mod): BigInteger
743
    {
744
        $exp = BigInteger::of($exp);
185✔
745
        $mod = BigInteger::of($mod);
185✔
746

747
        if ($exp->isNegative()) {
185✔
748
            throw new NegativeNumberException('The exponent cannot be negative.');
3✔
749
        }
750

751
        if ($mod->isNegative()) {
182✔
752
            throw new NegativeNumberException('The modulus cannot be negative.');
3✔
753
        }
754

755
        if ($mod->isZero()) {
179✔
756
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
757
        }
758

759
        $result = CalculatorRegistry::get()->modPow($this->value, $exp->value, $mod->value);
176✔
760

761
        return new BigInteger($result);
176✔
762
    }
763

764
    /**
765
     * Returns the greatest common divisor of this number and the given one.
766
     *
767
     * The GCD is always positive, unless both operands are zero, in which case it is zero.
768
     *
769
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
770
     *
771
     * @pure
772
     */
773
    public function gcd(BigNumber|int|float|string $that): BigInteger
774
    {
775
        $that = BigInteger::of($that);
3,210✔
776

777
        if ($that->value === '0' && $this->value[0] !== '-') {
3,210✔
778
            return $this;
66✔
779
        }
780

781
        if ($this->value === '0' && $that->value[0] !== '-') {
3,144✔
782
            return $that;
30✔
783
        }
784

785
        $value = CalculatorRegistry::get()->gcd($this->value, $that->value);
3,114✔
786

787
        return new BigInteger($value);
3,114✔
788
    }
789

790
    /**
791
     * Returns the least common multiple of this number and the given one.
792
     *
793
     * The LCM is always positive, unless at least one operand is zero, in which case it is zero.
794
     *
795
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
796
     *
797
     * @pure
798
     */
799
    public function lcm(BigNumber|int|float|string $that): BigInteger
800
    {
801
        $that = BigInteger::of($that);
561✔
802

803
        if ($this->isZero() || $that->isZero()) {
561✔
804
            return BigInteger::zero();
99✔
805
        }
806

807
        $value = CalculatorRegistry::get()->lcm($this->value, $that->value);
462✔
808

809
        return new BigInteger($value);
462✔
810
    }
811

812
    /**
813
     * Returns the integer square root of this number, rounded according to the given rounding mode.
814
     *
815
     * @param RoundingMode $roundingMode The rounding mode to use, defaults to Down.
816
     *                                   ⚠️ WARNING: the default rounding mode was kept as Down for backward
817
     *                                   compatibility, but will change to Unnecessary in version 0.15. Pass a rounding
818
     *                                   mode explicitly to avoid this upcoming breaking change.
819
     *
820
     * @throws NegativeNumberException    If this number is negative.
821
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, and the number is not a perfect square.
822
     *
823
     * @pure
824
     */
825
    public function sqrt(RoundingMode $roundingMode = RoundingMode::Down): BigInteger
826
    {
827
        if (func_num_args() === 0) {
10,626✔
828
            // @phpstan-ignore-next-line
829
            trigger_error(
6✔
830
                'The default rounding mode of BigInteger::sqrt() will change from Down to Unnecessary in version 0.15. ' .
6✔
831
                'Pass a rounding mode explicitly to avoid this breaking change.',
6✔
832
                E_USER_DEPRECATED,
6✔
833
            );
6✔
834
        }
835

836
        if ($this->value[0] === '-') {
10,626✔
837
            throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
3✔
838
        }
839

840
        $calculator = CalculatorRegistry::get();
10,623✔
841

842
        $sqrt = $calculator->sqrt($this->value);
10,623✔
843

844
        // For Down and Floor (equivalent for non-negative numbers), return floor sqrt
845
        if ($roundingMode === RoundingMode::Down || $roundingMode === RoundingMode::Floor) {
10,623✔
846
            return new BigInteger($sqrt);
2,133✔
847
        }
848

849
        // Check if the sqrt is exact
850
        $s2 = $calculator->mul($sqrt, $sqrt);
8,490✔
851
        $remainder = $calculator->sub($this->value, $s2);
8,490✔
852

853
        if ($remainder === '0') {
8,490✔
854
            // sqrt is exact
855
            return new BigInteger($sqrt);
5,385✔
856
        }
857

858
        // sqrt is not exact
859
        if ($roundingMode === RoundingMode::Unnecessary) {
3,105✔
860
            throw RoundingNecessaryException::roundingNecessary();
390✔
861
        }
862

863
        // For Up and Ceiling (equivalent for non-negative numbers), round up
864
        if ($roundingMode === RoundingMode::Up || $roundingMode === RoundingMode::Ceiling) {
2,715✔
865
            return new BigInteger($calculator->add($sqrt, '1'));
780✔
866
        }
867

868
        // For Half* modes, compare our number to the midpoint of the interval [s², (s+1)²[.
869
        // The midpoint is s² + s + 0.5. Comparing n >= s² + s + 0.5 with remainder = n − s²
870
        // is equivalent to comparing 2*remainder >= 2*s + 1.
871
        $twoRemainder = $calculator->mul($remainder, '2');
1,935✔
872
        $threshold = $calculator->add($calculator->mul($sqrt, '2'), '1');
1,935✔
873
        $cmp = $calculator->cmp($twoRemainder, $threshold);
1,935✔
874

875
        // We're supposed to increment (round up) when:
876
        //   - HalfUp, HalfCeiling => $cmp >= 0
877
        //   - HalfDown, HalfFloor => $cmp > 0
878
        //   - HalfEven => $cmp > 0 || ($cmp === 0 && $sqrt % 2 === 1)
879
        // But 2*remainder is always even and 2*s + 1 is always odd, so $cmp is never zero.
880
        // Therefore, all Half* modes simplify to:
881
        if ($cmp > 0) {
1,935✔
882
            $sqrt = $calculator->add($sqrt, '1');
990✔
883
        }
884

885
        return new BigInteger($sqrt);
1,935✔
886
    }
887

888
    public function negated(): static
889
    {
890
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
3,750✔
891
    }
892

893
    /**
894
     * Returns the integer bitwise-and combined with another integer.
895
     *
896
     * This method returns a negative BigInteger if and only if both operands are negative.
897
     *
898
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
899
     *
900
     * @pure
901
     */
902
    public function and(BigNumber|int|float|string $that): BigInteger
903
    {
904
        $that = BigInteger::of($that);
153✔
905

906
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
907
    }
908

909
    /**
910
     * Returns the integer bitwise-or combined with another integer.
911
     *
912
     * This method returns a negative BigInteger if and only if either of the operands is negative.
913
     *
914
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
915
     *
916
     * @pure
917
     */
918
    public function or(BigNumber|int|float|string $that): BigInteger
919
    {
920
        $that = BigInteger::of($that);
138✔
921

922
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
923
    }
924

925
    /**
926
     * Returns the integer bitwise-xor combined with another integer.
927
     *
928
     * This method returns a negative BigInteger if and only if exactly one of the operands is negative.
929
     *
930
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
931
     *
932
     * @pure
933
     */
934
    public function xor(BigNumber|int|float|string $that): BigInteger
935
    {
936
        $that = BigInteger::of($that);
144✔
937

938
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
939
    }
940

941
    /**
942
     * Returns the bitwise-not of this BigInteger.
943
     *
944
     * @pure
945
     */
946
    public function not(): BigInteger
947
    {
948
        return $this->negated()->minus(1);
57✔
949
    }
950

951
    /**
952
     * Returns the integer left shifted by a given number of bits.
953
     *
954
     * @pure
955
     */
956
    public function shiftedLeft(int $distance): BigInteger
957
    {
958
        if ($distance === 0) {
594✔
959
            return $this;
6✔
960
        }
961

962
        if ($distance < 0) {
588✔
963
            return $this->shiftedRight(-$distance);
198✔
964
        }
965

966
        return $this->multipliedBy(BigInteger::of(2)->power($distance));
390✔
967
    }
968

969
    /**
970
     * Returns the integer right shifted by a given number of bits.
971
     *
972
     * @pure
973
     */
974
    public function shiftedRight(int $distance): BigInteger
975
    {
976
        if ($distance === 0) {
1,518✔
977
            return $this;
66✔
978
        }
979

980
        if ($distance < 0) {
1,452✔
981
            return $this->shiftedLeft(-$distance);
195✔
982
        }
983

984
        $operand = BigInteger::of(2)->power($distance);
1,257✔
985

986
        if ($this->isPositiveOrZero()) {
1,257✔
987
            return $this->quotient($operand);
672✔
988
        }
989

990
        return $this->dividedBy($operand, RoundingMode::Up);
585✔
991
    }
992

993
    /**
994
     * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
995
     *
996
     * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation.
997
     * Computes (ceil(log2(this < 0 ? -this : this+1))).
998
     *
999
     * @pure
1000
     */
1001
    public function getBitLength(): int
1002
    {
1003
        if ($this->value === '0') {
321✔
1004
            return 0;
12✔
1005
        }
1006

1007
        if ($this->isNegative()) {
315✔
1008
            return $this->abs()->minus(1)->getBitLength();
120✔
1009
        }
1010

1011
        return strlen($this->toBase(2));
309✔
1012
    }
1013

1014
    /**
1015
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
1016
     *
1017
     * Returns -1 if this BigInteger contains no one bits.
1018
     *
1019
     * @pure
1020
     */
1021
    public function getLowestSetBit(): int
1022
    {
1023
        $n = $this;
81✔
1024
        $bitLength = $this->getBitLength();
81✔
1025

1026
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
1027
            if ($n->isOdd()) {
81✔
1028
                return $i;
78✔
1029
            }
1030

1031
            $n = $n->shiftedRight(1);
51✔
1032
        }
1033

1034
        return -1;
3✔
1035
    }
1036

1037
    /**
1038
     * Returns whether this number is even.
1039
     *
1040
     * @pure
1041
     */
1042
    public function isEven(): bool
1043
    {
1044
        return in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
1045
    }
1046

1047
    /**
1048
     * Returns whether this number is odd.
1049
     *
1050
     * @pure
1051
     */
1052
    public function isOdd(): bool
1053
    {
1054
        return in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
1055
    }
1056

1057
    /**
1058
     * Returns true if and only if the designated bit is set.
1059
     *
1060
     * Computes ((this & (1<<n)) != 0).
1061
     *
1062
     * @param int $n The bit to test, 0-based.
1063
     *
1064
     * @throws InvalidArgumentException If the bit to test is negative.
1065
     *
1066
     * @pure
1067
     */
1068
    public function testBit(int $n): bool
1069
    {
1070
        if ($n < 0) {
873✔
1071
            throw new InvalidArgumentException('The bit to test cannot be negative.');
3✔
1072
        }
1073

1074
        return $this->shiftedRight($n)->isOdd();
870✔
1075
    }
1076

1077
    #[Override]
1078
    public function compareTo(BigNumber|int|float|string $that): int
1079
    {
1080
        $that = BigNumber::of($that);
2,327✔
1081

1082
        if ($that instanceof BigInteger) {
2,327✔
1083
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,219✔
1084
        }
1085

1086
        return -$that->compareTo($this);
108✔
1087
    }
1088

1089
    #[Override]
1090
    public function getSign(): int
1091
    {
1092
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
5,891✔
1093
    }
1094

1095
    #[Override]
1096
    public function toBigInteger(): BigInteger
1097
    {
1098
        return $this;
23,855✔
1099
    }
1100

1101
    #[Override]
1102
    public function toBigDecimal(): BigDecimal
1103
    {
1104
        return self::newBigDecimal($this->value);
5,316✔
1105
    }
1106

1107
    #[Override]
1108
    public function toBigRational(): BigRational
1109
    {
1110
        return self::newBigRational($this, BigInteger::one(), false);
471✔
1111
    }
1112

1113
    #[Override]
1114
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
1115
    {
1116
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
1117
    }
1118

1119
    #[Override]
1120
    public function toInt(): int
1121
    {
1122
        $intValue = filter_var($this->value, FILTER_VALIDATE_INT);
87✔
1123

1124
        if ($intValue === false) {
87✔
1125
            throw IntegerOverflowException::toIntOverflow($this);
15✔
1126
        }
1127

1128
        return $intValue;
72✔
1129
    }
1130

1131
    #[Override]
1132
    public function toFloat(): float
1133
    {
1134
        return (float) $this->value;
48✔
1135
    }
1136

1137
    /**
1138
     * Returns a string representation of this number in the given base.
1139
     *
1140
     * The output will always be lowercase for bases greater than 10.
1141
     *
1142
     * @throws InvalidArgumentException If the base is out of range.
1143
     *
1144
     * @pure
1145
     */
1146
    public function toBase(int $base): string
1147
    {
1148
        if ($base === 10) {
1,293✔
1149
            return $this->value;
12✔
1150
        }
1151

1152
        if ($base < 2 || $base > 36) {
1,281✔
1153
            throw new InvalidArgumentException(sprintf('Base %d is out of range [2, 36]', $base));
15✔
1154
        }
1155

1156
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,266✔
1157
    }
1158

1159
    /**
1160
     * Returns a string representation of this number in an arbitrary base with a custom alphabet.
1161
     *
1162
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers;
1163
     * a NegativeNumberException will be thrown when attempting to call this method on a negative number.
1164
     *
1165
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
1166
     *
1167
     * @throws NegativeNumberException  If this number is negative.
1168
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars, or contains duplicates.
1169
     *
1170
     * @pure
1171
     */
1172
    public function toArbitraryBase(string $alphabet): string
1173
    {
1174
        $base = strlen($alphabet);
144✔
1175

1176
        if ($base < 2) {
144✔
1177
            throw new InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
1178
        }
1179

1180
        if (strlen(count_chars($alphabet, 3)) !== $base) {
138✔
1181
            throw new InvalidArgumentException('The alphabet must not contain duplicate chars.');
9✔
1182
        }
1183

1184
        if ($this->value[0] === '-') {
129✔
1185
            throw new NegativeNumberException(__FUNCTION__ . '() does not support negative numbers.');
3✔
1186
        }
1187

1188
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1189
    }
1190

1191
    /**
1192
     * Returns a string of bytes containing the binary representation of this BigInteger.
1193
     *
1194
     * The string is in big-endian byte-order: the most significant byte is in the zeroth element.
1195
     *
1196
     * If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to
1197
     * the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the
1198
     * number is negative.
1199
     *
1200
     * The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit
1201
     * if `$signed` is true.
1202
     *
1203
     * This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match.
1204
     *
1205
     * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit.
1206
     *
1207
     * @throws NegativeNumberException If $signed is false, and the number is negative.
1208
     *
1209
     * @pure
1210
     */
1211
    public function toBytes(bool $signed = true): string
1212
    {
1213
        if (! $signed && $this->isNegative()) {
534✔
1214
            throw new NegativeNumberException('Cannot convert a negative number to a byte string when $signed is false.');
3✔
1215
        }
1216

1217
        $hex = $this->abs()->toBase(16);
531✔
1218

1219
        if (strlen($hex) % 2 !== 0) {
531✔
1220
            $hex = '0' . $hex;
219✔
1221
        }
1222

1223
        $baseHexLength = strlen($hex);
531✔
1224

1225
        if ($signed) {
531✔
1226
            if ($this->isNegative()) {
492✔
1227
                $bin = hex2bin($hex);
453✔
1228
                assert($bin !== false);
1229

1230
                $hex = bin2hex(~$bin);
453✔
1231
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1232

1233
                $hexLength = strlen($hex);
453✔
1234

1235
                if ($hexLength < $baseHexLength) {
453✔
1236
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1237
                }
1238

1239
                if ($hex[0] < '8') {
453✔
1240
                    $hex = 'FF' . $hex;
114✔
1241
                }
1242
            } else {
1243
                if ($hex[0] >= '8') {
39✔
1244
                    $hex = '00' . $hex;
21✔
1245
                }
1246
            }
1247
        }
1248

1249
        $result = hex2bin($hex);
531✔
1250
        assert($result !== false);
1251

1252
        return $result;
531✔
1253
    }
1254

1255
    /**
1256
     * @return numeric-string
1257
     */
1258
    #[Override]
1259
    public function __toString(): string
1260
    {
1261
        /** @var numeric-string */
1262
        return $this->value;
23,760✔
1263
    }
1264

1265
    /**
1266
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1267
     *
1268
     * @internal
1269
     *
1270
     * @return array{value: string}
1271
     */
1272
    public function __serialize(): array
1273
    {
1274
        return ['value' => $this->value];
6✔
1275
    }
1276

1277
    /**
1278
     * This method is only here to allow unserializing the object and cannot be accessed directly.
1279
     *
1280
     * @internal
1281
     *
1282
     * @param array{value: string} $data
1283
     *
1284
     * @throws LogicException
1285
     */
1286
    public function __unserialize(array $data): void
1287
    {
1288
        /** @phpstan-ignore isset.initializedProperty */
1289
        if (isset($this->value)) {
9✔
1290
            throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
1291
        }
1292

1293
        /** @phpstan-ignore deadCode.unreachable */
1294
        $this->value = $data['value'];
6✔
1295
    }
1296

1297
    #[Override]
1298
    protected static function from(BigNumber $number): static
1299
    {
1300
        return $number->toBigInteger();
23,975✔
1301
    }
1302
}
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