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

brick / math / 21705268904

05 Feb 2026 09:01AM UTC coverage: 99.289% (-0.004%) from 99.293%
21705268904

push

github

BenMorel
Minor documentation tweaks

2 of 2 new or added lines in 1 file covered. (100.0%)

3 existing lines in 1 file now uncovered.

1257 of 1266 relevant lines covered (99.29%)

2506.17 hits per line

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

99.05
/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\InvalidArgumentException;
10
use Brick\Math\Exception\MathException;
11
use Brick\Math\Exception\NegativeNumberException;
12
use Brick\Math\Exception\NoInverseException;
13
use Brick\Math\Exception\NumberFormatException;
14
use Brick\Math\Exception\RoundingNecessaryException;
15
use Brick\Math\Internal\Calculator;
16
use Brick\Math\Internal\CalculatorRegistry;
17
use LogicException;
18
use Override;
19

20
use function assert;
21
use function bin2hex;
22
use function chr;
23
use function count_chars;
24
use function filter_var;
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

39
use const FILTER_VALIDATE_INT;
40

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

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

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

93
        if ($base < 2 || $base > 36) {
2,090✔
94
            throw new InvalidArgumentException(sprintf('Base %d is out of range [2, 36].', $base));
15✔
95
        }
96

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

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

111
        $number = ltrim($number, '0');
2,069✔
112

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

207
        $twosComplement = false;
1,221✔
208

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

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

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

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

223
        return $number;
315✔
224
    }
225

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

319
        return $zero;
222✔
320
    }
321

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

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

336
        return $one;
519✔
337
    }
338

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

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

353
        return $ten;
6✔
354
    }
355

356
    /**
357
     * Returns the greatest common divisor of the given numbers.
358
     *
359
     * The GCD is always positive, unless all numbers are zero, in which case it is zero.
360
     *
361
     * @param BigNumber|int|string $a    The first number. Must be convertible to a BigInteger.
362
     * @param BigNumber|int|string ...$n The subsequent numbers. Must be convertible to BigInteger.
363
     *
364
     * @throws MathException If one of the parameters cannot be converted to a BigInteger.
365
     *
366
     * @pure
367
     */
368
    public static function gcdAll(BigNumber|int|string $a, BigNumber|int|string ...$n): BigInteger
369
    {
370
        $result = BigInteger::of($a)->abs();
1,587✔
371

372
        foreach ($n as $next) {
1,587✔
373
            $result = $result->gcd(BigInteger::of($next));
1,560✔
374

375
            if ($result->isEqualTo(1)) {
1,560✔
376
                return $result;
345✔
377
            }
378
        }
379

380
        return $result;
1,242✔
381
    }
382

383
    /**
384
     * Returns the least common multiple of the given numbers.
385
     *
386
     * The LCM is always positive, unless one of the numbers is zero, in which case it is zero.
387
     *
388
     * @param BigNumber|int|string $a    The first number. Must be convertible to a BigInteger.
389
     * @param BigNumber|int|string ...$n The subsequent numbers. Must be convertible to BigInteger.
390
     *
391
     * @throws MathException If one of the parameters cannot be converted to a BigInteger.
392
     *
393
     * @pure
394
     */
395
    public static function lcmAll(BigNumber|int|string $a, BigNumber|int|string ...$n): BigInteger
396
    {
397
        $result = BigInteger::of($a)->abs();
324✔
398

399
        foreach ($n as $next) {
324✔
400
            $result = $result->lcm(BigInteger::of($next));
297✔
401

402
            if ($result->isZero()) {
297✔
403
                return $result;
51✔
404
            }
405
        }
406

407
        return $result;
273✔
408
    }
409

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

423
        if ($that->value === '0') {
1,629✔
424
            return $this;
30✔
425
        }
426

427
        if ($this->value === '0') {
1,599✔
428
            return $that;
72✔
429
        }
430

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

433
        return new BigInteger($value);
1,548✔
434
    }
435

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

449
        if ($that->value === '0') {
990✔
450
            return $this;
30✔
451
        }
452

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

455
        return new BigInteger($value);
969✔
456
    }
457

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

471
        if ($that->value === '1') {
1,332✔
472
            return $this;
417✔
473
        }
474

475
        if ($this->value === '1') {
1,266✔
476
            return $that;
408✔
477
        }
478

479
        $value = CalculatorRegistry::get()->mul($this->value, $that->value);
1,158✔
480

481
        return new BigInteger($value);
1,158✔
482
    }
483

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

499
        if ($that->value === '1') {
1,968✔
500
            return $this;
3✔
501
        }
502

503
        if ($that->value === '0') {
1,965✔
504
            throw DivisionByZeroException::divisionByZero();
6✔
505
        }
506

507
        $result = CalculatorRegistry::get()->divRound($this->value, $that->value, $roundingMode);
1,959✔
508

509
        return new BigInteger($result);
1,866✔
510
    }
511

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

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

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

542
        return $this;
18✔
543
    }
544

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

558
        if ($exponent === 1) {
1,824✔
559
            return $this;
204✔
560
        }
561

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

570
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,614✔
571
    }
572

573
    /**
574
     * Returns the quotient of the division of this number by the given one.
575
     *
576
     * Examples:
577
     *
578
     * - `7` quotient `3` returns `2`
579
     * - `7` quotient `-3` returns `-2`
580
     * - `-7` quotient `3` returns `-2`
581
     * - `-7` quotient `-3` returns `2`
582
     *
583
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
584
     *
585
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
586
     * @throws DivisionByZeroException If the divisor is zero.
587
     *
588
     * @pure
589
     */
590
    public function quotient(BigNumber|int|string $that): BigInteger
591
    {
592
        $that = BigInteger::of($that);
2,802✔
593

594
        if ($that->value === '1') {
2,802✔
595
            return $this;
1,470✔
596
        }
597

598
        if ($that->value === '0') {
1,923✔
599
            throw DivisionByZeroException::divisionByZero();
3✔
600
        }
601

602
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
1,920✔
603

604
        return new BigInteger($quotient);
1,920✔
605
    }
606

607
    /**
608
     * Returns the remainder of the division of this number by the given one.
609
     *
610
     * The remainder, when non-zero, has the same sign as the dividend.
611
     *
612
     * Examples:
613
     *
614
     * - `7` remainder `3` returns `1`
615
     * - `7` remainder `-3` returns `1`
616
     * - `-7` remainder `3` returns `-1`
617
     * - `-7` remainder `-3` returns `-1`
618
     *
619
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
620
     *
621
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
622
     * @throws DivisionByZeroException If the divisor is zero.
623
     *
624
     * @pure
625
     */
626
    public function remainder(BigNumber|int|string $that): BigInteger
627
    {
628
        $that = BigInteger::of($that);
273✔
629

630
        if ($that->value === '1') {
273✔
631
            return BigInteger::zero();
24✔
632
        }
633

634
        if ($that->value === '0') {
249✔
635
            throw DivisionByZeroException::divisionByZero();
3✔
636
        }
637

638
        $remainder = CalculatorRegistry::get()->divR($this->value, $that->value);
246✔
639

640
        return new BigInteger($remainder);
246✔
641
    }
642

643
    /**
644
     * Returns the quotient and remainder of the division of this number by the given one.
645
     *
646
     * Examples:
647
     *
648
     * - `7` quotientAndRemainder `3` returns [`2`, `1`]
649
     * - `7` quotientAndRemainder `-3` returns [`-2`, `1`]
650
     * - `-7` quotientAndRemainder `3` returns [`-2`, `-1`]
651
     * - `-7` quotientAndRemainder `-3` returns [`2`, `-1`]
652
     *
653
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
654
     *
655
     * @return array{BigInteger, BigInteger} An array containing the quotient and the remainder.
656
     *
657
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
658
     * @throws DivisionByZeroException If the divisor is zero.
659
     *
660
     * @pure
661
     */
662
    public function quotientAndRemainder(BigNumber|int|string $that): array
663
    {
664
        $that = BigInteger::of($that);
147✔
665

666
        if ($that->value === '0') {
147✔
667
            throw DivisionByZeroException::divisionByZero();
3✔
668
        }
669

670
        [$quotient, $remainder] = CalculatorRegistry::get()->divQR($this->value, $that->value);
144✔
671

672
        return [
144✔
673
            new BigInteger($quotient),
144✔
674
            new BigInteger($remainder),
144✔
675
        ];
144✔
676
    }
677

678
    /**
679
     * Returns this number modulo the given one.
680
     *
681
     * The result is always non-negative, and is the unique value `r` such that `0 <= r < m`
682
     * and `this - r` is a multiple of `m`.
683
     *
684
     * This is also known as Euclidean modulo. Unlike `remainder()`, which can return negative values
685
     * when the dividend is negative, `mod()` always returns a non-negative result.
686
     *
687
     * Examples:
688
     *
689
     * - `7` mod `3` returns `1`
690
     * - `-7` mod `3` returns `2`
691
     *
692
     * @param BigNumber|int|string $modulus The modulus, strictly positive. Must be convertible to a BigInteger.
693
     *
694
     * @throws MathException           If the modulus is not valid, or is not convertible to a BigInteger.
695
     * @throws DivisionByZeroException If the modulus is zero.
696
     * @throws NegativeNumberException If the modulus is negative.
697
     *
698
     * @pure
699
     */
700
    public function mod(BigNumber|int|string $modulus): BigInteger
701
    {
702
        $modulus = BigInteger::of($modulus);
105✔
703

704
        if ($modulus->isZero()) {
105✔
705
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
706
        }
707

708
        if ($modulus->isNegative()) {
102✔
709
            throw new NegativeNumberException('Modulus must be strictly positive.');
3✔
710
        }
711

712
        $value = CalculatorRegistry::get()->mod($this->value, $modulus->value);
99✔
713

714
        return new BigInteger($value);
99✔
715
    }
716

717
    /**
718
     * Returns the modular multiplicative inverse of this BigInteger modulo $modulus.
719
     *
720
     * @param BigNumber|int|string $modulus The modulus. Must be convertible to a BigInteger.
721
     *
722
     * @throws DivisionByZeroException If $modulus is zero.
723
     * @throws NegativeNumberException If $modulus is negative.
724
     * @throws MathException           If this BigInteger has no multiplicative inverse mod m (that is, this BigInteger
725
     *                                 is not relatively prime to m).
726
     *
727
     * @pure
728
     */
729
    public function modInverse(BigNumber|int|string $modulus): BigInteger
730
    {
731
        $modulus = BigInteger::of($modulus);
75✔
732

733
        if ($modulus->isZero()) {
75✔
734
            throw DivisionByZeroException::modulusMustNotBeZero();
6✔
735
        }
736

737
        if ($modulus->isNegative()) {
69✔
738
            throw new NegativeNumberException('Modulus must be strictly positive.');
3✔
739
        }
740

741
        if ($modulus->value === '1') {
66✔
742
            return BigInteger::zero();
3✔
743
        }
744

745
        $value = CalculatorRegistry::get()->modInverse($this->value, $modulus->value);
63✔
746

747
        if ($value === null) {
63✔
748
            throw NoInverseException::noModularInverse();
15✔
749
        }
750

751
        return new BigInteger($value);
48✔
752
    }
753

754
    /**
755
     * Returns this number raised into power with modulo.
756
     *
757
     * This operation requires a non-negative exponent and a strictly positive modulus.
758
     *
759
     * @param BigNumber|int|string $exponent The exponent. Must be positive or zero.
760
     * @param BigNumber|int|string $modulus  The modulus. Must be strictly positive.
761
     *
762
     * @throws MathException           If the exponent or modulus is not valid, or not convertible to a BigInteger.
763
     * @throws NegativeNumberException If the exponent or modulus is negative.
764
     * @throws DivisionByZeroException If the modulus is zero.
765
     *
766
     * @pure
767
     */
768
    public function modPow(BigNumber|int|string $exponent, BigNumber|int|string $modulus): BigInteger
769
    {
770
        $exponent = BigInteger::of($exponent);
185✔
771
        $modulus = BigInteger::of($modulus);
185✔
772

773
        if ($exponent->isNegative()) {
185✔
774
            throw new NegativeNumberException('Exponent must not be negative.');
3✔
775
        }
776

777
        if ($modulus->isZero()) {
182✔
778
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
779
        }
780

781
        if ($modulus->isNegative()) {
179✔
782
            throw new NegativeNumberException('Modulus must be strictly positive.');
3✔
783
        }
784

785
        $result = CalculatorRegistry::get()->modPow($this->value, $exponent->value, $modulus->value);
176✔
786

787
        return new BigInteger($result);
176✔
788
    }
789

790
    /**
791
     * Returns the greatest common divisor of this number and the given one.
792
     *
793
     * The GCD is always positive, unless both operands are zero, in which case it is zero.
794
     *
795
     * @param BigNumber|int|string $that The operand. Must be convertible to a BigInteger.
796
     *
797
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
798
     *
799
     * @pure
800
     */
801
    public function gcd(BigNumber|int|string $that): BigInteger
802
    {
803
        $that = BigInteger::of($that);
5,055✔
804

805
        if ($that->value === '0' && $this->value[0] !== '-') {
5,055✔
806
            return $this;
66✔
807
        }
808

809
        if ($this->value === '0' && $that->value[0] !== '-') {
4,989✔
810
            return $that;
300✔
811
        }
812

813
        $value = CalculatorRegistry::get()->gcd($this->value, $that->value);
4,899✔
814

815
        return new BigInteger($value);
4,899✔
816
    }
817

818
    /**
819
     * Returns the least common multiple of this number and the given one.
820
     *
821
     * The LCM is always positive, unless at least one operand is zero, in which case it is zero.
822
     *
823
     * @param BigNumber|int|string $that The operand. Must be convertible to a BigInteger.
824
     *
825
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
826
     *
827
     * @pure
828
     */
829
    public function lcm(BigNumber|int|string $that): BigInteger
830
    {
831
        $that = BigInteger::of($that);
561✔
832

833
        if ($this->isZero() || $that->isZero()) {
561✔
834
            return BigInteger::zero();
99✔
835
        }
836

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

839
        return new BigInteger($value);
462✔
840
    }
841

842
    /**
843
     * Returns the integer square root of this number, rounded according to the given rounding mode.
844
     *
845
     * @param RoundingMode $roundingMode The rounding mode to use, defaults to Unnecessary.
846
     *
847
     * @throws NegativeNumberException    If this number is negative.
848
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, and the number is not a perfect square.
849
     *
850
     * @pure
851
     */
852
    public function sqrt(RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
853
    {
854
        if ($this->value[0] === '-') {
10,623✔
855
            throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
3✔
856
        }
857

858
        $calculator = CalculatorRegistry::get();
10,620✔
859

860
        $sqrt = $calculator->sqrt($this->value);
10,620✔
861

862
        // For Down and Floor (equivalent for non-negative numbers), return floor sqrt
863
        if ($roundingMode === RoundingMode::Down || $roundingMode === RoundingMode::Floor) {
10,620✔
864
            return new BigInteger($sqrt);
2,130✔
865
        }
866

867
        // Check if the sqrt is exact
868
        $s2 = $calculator->mul($sqrt, $sqrt);
8,490✔
869
        $remainder = $calculator->sub($this->value, $s2);
8,490✔
870

871
        if ($remainder === '0') {
8,490✔
872
            // sqrt is exact
873
            return new BigInteger($sqrt);
5,385✔
874
        }
875

876
        // sqrt is not exact
877
        if ($roundingMode === RoundingMode::Unnecessary) {
3,105✔
878
            throw RoundingNecessaryException::roundingNecessary();
390✔
879
        }
880

881
        // For Up and Ceiling (equivalent for non-negative numbers), round up
882
        if ($roundingMode === RoundingMode::Up || $roundingMode === RoundingMode::Ceiling) {
2,715✔
883
            return new BigInteger($calculator->add($sqrt, '1'));
780✔
884
        }
885

886
        // For Half* modes, compare our number to the midpoint of the interval [s², (s+1)²[.
887
        // The midpoint is s² + s + 0.5. Comparing n >= s² + s + 0.5 with remainder = n − s²
888
        // is equivalent to comparing 2*remainder >= 2*s + 1.
889
        $twoRemainder = $calculator->mul($remainder, '2');
1,935✔
890
        $threshold = $calculator->add($calculator->mul($sqrt, '2'), '1');
1,935✔
891
        $cmp = $calculator->cmp($twoRemainder, $threshold);
1,935✔
892

893
        // We're supposed to increment (round up) when:
894
        //   - HalfUp, HalfCeiling => $cmp >= 0
895
        //   - HalfDown, HalfFloor => $cmp > 0
896
        //   - HalfEven => $cmp > 0 || ($cmp === 0 && $sqrt % 2 === 1)
897
        // But 2*remainder is always even and 2*s + 1 is always odd, so $cmp is never zero.
898
        // Therefore, all Half* modes simplify to:
899
        if ($cmp > 0) {
1,935✔
900
            $sqrt = $calculator->add($sqrt, '1');
990✔
901
        }
902

903
        return new BigInteger($sqrt);
1,935✔
904
    }
905

906
    public function negated(): static
907
    {
908
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
3,798✔
909
    }
910

911
    /**
912
     * Returns the integer bitwise-and combined with another integer.
913
     *
914
     * This method returns a negative BigInteger if and only if both operands are negative.
915
     *
916
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
917
     *
918
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
919
     *
920
     * @pure
921
     */
922
    public function and(BigNumber|int|string $that): BigInteger
923
    {
924
        $that = BigInteger::of($that);
153✔
925

926
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
927
    }
928

929
    /**
930
     * Returns the integer bitwise-or combined with another integer.
931
     *
932
     * This method returns a negative BigInteger if and only if either of the operands is negative.
933
     *
934
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
935
     *
936
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
937
     *
938
     * @pure
939
     */
940
    public function or(BigNumber|int|string $that): BigInteger
941
    {
942
        $that = BigInteger::of($that);
138✔
943

944
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
945
    }
946

947
    /**
948
     * Returns the integer bitwise-xor combined with another integer.
949
     *
950
     * This method returns a negative BigInteger if and only if exactly one of the operands is negative.
951
     *
952
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
953
     *
954
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
955
     *
956
     * @pure
957
     */
958
    public function xor(BigNumber|int|string $that): BigInteger
959
    {
960
        $that = BigInteger::of($that);
144✔
961

962
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
963
    }
964

965
    /**
966
     * Returns the bitwise-not of this BigInteger.
967
     *
968
     * @pure
969
     */
970
    public function not(): BigInteger
971
    {
972
        return $this->negated()->minus(1);
57✔
973
    }
974

975
    /**
976
     * Returns the integer left shifted by a given number of bits.
977
     *
978
     * @throws InvalidArgumentException If the number of bits is out of range.
979
     *
980
     * @pure
981
     */
982
    public function shiftedLeft(int $bits): BigInteger
983
    {
984
        if ($bits === 0) {
594✔
985
            return $this;
6✔
986
        }
987

988
        if ($bits < 0) {
588✔
989
            return $this->shiftedRight(-$bits);
198✔
990
        }
991

992
        return $this->multipliedBy(BigInteger::of(2)->power($bits));
390✔
993
    }
994

995
    /**
996
     * Returns the integer right shifted by a given number of bits.
997
     *
998
     * @throws InvalidArgumentException If the number of bits is out of range.
999
     *
1000
     * @pure
1001
     */
1002
    public function shiftedRight(int $bits): BigInteger
1003
    {
1004
        if ($bits === 0) {
1,518✔
1005
            return $this;
66✔
1006
        }
1007

1008
        if ($bits < 0) {
1,452✔
1009
            return $this->shiftedLeft(-$bits);
195✔
1010
        }
1011

1012
        $operand = BigInteger::of(2)->power($bits);
1,257✔
1013

1014
        if ($this->isPositiveOrZero()) {
1,257✔
1015
            return $this->quotient($operand);
672✔
1016
        }
1017

1018
        return $this->dividedBy($operand, RoundingMode::Up);
585✔
1019
    }
1020

1021
    /**
1022
     * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
1023
     *
1024
     * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation.
1025
     * Computes (ceil(log2(this < 0 ? -this : this+1))).
1026
     *
1027
     * @pure
1028
     */
1029
    public function getBitLength(): int
1030
    {
1031
        if ($this->value === '0') {
321✔
1032
            return 0;
12✔
1033
        }
1034

1035
        if ($this->isNegative()) {
315✔
1036
            return $this->abs()->minus(1)->getBitLength();
120✔
1037
        }
1038

1039
        return strlen($this->toBase(2));
309✔
1040
    }
1041

1042
    /**
1043
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
1044
     *
1045
     * Returns -1 if this BigInteger contains no one bits.
1046
     *
1047
     * @pure
1048
     */
1049
    public function getLowestSetBit(): int
1050
    {
1051
        $n = $this;
81✔
1052
        $bitLength = $this->getBitLength();
81✔
1053

1054
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
1055
            if ($n->isOdd()) {
81✔
1056
                return $i;
78✔
1057
            }
1058

1059
            $n = $n->shiftedRight(1);
51✔
1060
        }
1061

1062
        return -1;
3✔
1063
    }
1064

1065
    /**
1066
     * Returns whether this number is even.
1067
     *
1068
     * @pure
1069
     */
1070
    public function isEven(): bool
1071
    {
1072
        return in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
1073
    }
1074

1075
    /**
1076
     * Returns whether this number is odd.
1077
     *
1078
     * @pure
1079
     */
1080
    public function isOdd(): bool
1081
    {
1082
        return in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
1083
    }
1084

1085
    /**
1086
     * Returns true if and only if the designated bit is set.
1087
     *
1088
     * Computes ((this & (1<<n)) != 0).
1089
     *
1090
     * @param int $n The bit to test, 0-based.
1091
     *
1092
     * @throws InvalidArgumentException If the bit to test is negative.
1093
     *
1094
     * @pure
1095
     */
1096
    public function testBit(int $n): bool
1097
    {
1098
        if ($n < 0) {
873✔
1099
            throw new InvalidArgumentException('The bit to test cannot be negative.');
3✔
1100
        }
1101

1102
        return $this->shiftedRight($n)->isOdd();
870✔
1103
    }
1104

1105
    #[Override]
1106
    public function compareTo(BigNumber|int|string $that): int
1107
    {
1108
        $that = BigNumber::of($that);
2,327✔
1109

1110
        if ($that instanceof BigInteger) {
2,327✔
1111
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,219✔
1112
        }
1113

1114
        return -$that->compareTo($this);
108✔
1115
    }
1116

1117
    #[Override]
1118
    public function getSign(): int
1119
    {
1120
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
5,894✔
1121
    }
1122

1123
    #[Override]
1124
    public function toBigInteger(): BigInteger
1125
    {
1126
        return $this;
24,602✔
1127
    }
1128

1129
    #[Override]
1130
    public function toBigDecimal(): BigDecimal
1131
    {
1132
        return self::newBigDecimal($this->value);
5,259✔
1133
    }
1134

1135
    #[Override]
1136
    public function toBigRational(): BigRational
1137
    {
1138
        return self::newBigRational($this, BigInteger::one(), false, false);
477✔
1139
    }
1140

1141
    #[Override]
1142
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
1143
    {
1144
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
1145
    }
1146

1147
    #[Override]
1148
    public function toInt(): int
1149
    {
1150
        $intValue = filter_var($this->value, FILTER_VALIDATE_INT);
87✔
1151

1152
        if ($intValue === false) {
87✔
1153
            throw IntegerOverflowException::toIntOverflow($this);
15✔
1154
        }
1155

1156
        return $intValue;
72✔
1157
    }
1158

1159
    #[Override]
1160
    public function toFloat(): float
1161
    {
1162
        return (float) $this->value;
183✔
1163
    }
1164

1165
    /**
1166
     * Returns a string representation of this number in the given base.
1167
     *
1168
     * The output will always be lowercase for bases greater than 10.
1169
     *
1170
     * @throws InvalidArgumentException If the base is out of range.
1171
     *
1172
     * @pure
1173
     */
1174
    public function toBase(int $base): string
1175
    {
1176
        if ($base === 10) {
1,293✔
1177
            return $this->value;
12✔
1178
        }
1179

1180
        if ($base < 2 || $base > 36) {
1,281✔
1181
            throw new InvalidArgumentException(sprintf('Base %d is out of range [2, 36].', $base));
15✔
1182
        }
1183

1184
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,266✔
1185
    }
1186

1187
    /**
1188
     * Returns a string representation of this number in an arbitrary base with a custom alphabet.
1189
     *
1190
     * This method is byte-oriented: the alphabet is interpreted as a sequence of single-byte characters.
1191
     * Multibyte UTF-8 characters are not supported.
1192
     *
1193
     * Because this method accepts any single-byte character, including dash, it does not handle negative numbers;
1194
     * a NegativeNumberException will be thrown when attempting to call this method on a negative number.
1195
     *
1196
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
1197
     *
1198
     * @throws NegativeNumberException  If this number is negative.
1199
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars, or contains duplicates.
1200
     *
1201
     * @pure
1202
     */
1203
    public function toArbitraryBase(string $alphabet): string
1204
    {
1205
        $base = strlen($alphabet);
144✔
1206

1207
        if ($base < 2) {
144✔
1208
            throw new InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
1209
        }
1210

1211
        if (strlen(count_chars($alphabet, 3)) !== $base) {
138✔
1212
            throw new InvalidArgumentException('The alphabet must not contain duplicate chars.');
9✔
1213
        }
1214

1215
        if ($this->value[0] === '-') {
129✔
1216
            throw new NegativeNumberException(__FUNCTION__ . '() does not support negative numbers.');
3✔
1217
        }
1218

1219
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1220
    }
1221

1222
    /**
1223
     * Returns a string of bytes containing the binary representation of this BigInteger.
1224
     *
1225
     * The string is in big-endian byte-order: the most significant byte is in the zeroth element.
1226
     *
1227
     * If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to
1228
     * the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the
1229
     * number is negative.
1230
     *
1231
     * The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit
1232
     * if `$signed` is true.
1233
     *
1234
     * This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match.
1235
     *
1236
     * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit.
1237
     *
1238
     * @throws NegativeNumberException If $signed is false, and the number is negative.
1239
     *
1240
     * @pure
1241
     */
1242
    public function toBytes(bool $signed = true): string
1243
    {
1244
        if (! $signed && $this->isNegative()) {
534✔
1245
            throw new NegativeNumberException('Cannot convert a negative number to a byte string when $signed is false.');
3✔
1246
        }
1247

1248
        $hex = $this->abs()->toBase(16);
531✔
1249

1250
        if (strlen($hex) % 2 !== 0) {
531✔
1251
            $hex = '0' . $hex;
219✔
1252
        }
1253

1254
        $baseHexLength = strlen($hex);
531✔
1255

1256
        if ($signed) {
531✔
1257
            if ($this->isNegative()) {
492✔
1258
                $bin = hex2bin($hex);
453✔
1259
                assert($bin !== false);
1260

1261
                $hex = bin2hex(~$bin);
453✔
1262
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1263

1264
                $hexLength = strlen($hex);
453✔
1265

1266
                if ($hexLength < $baseHexLength) {
453✔
1267
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1268
                }
1269

1270
                if ($hex[0] < '8') {
453✔
1271
                    $hex = 'FF' . $hex;
114✔
1272
                }
1273
            } else {
1274
                if ($hex[0] >= '8') {
39✔
1275
                    $hex = '00' . $hex;
21✔
1276
                }
1277
            }
1278
        }
1279

1280
        $result = hex2bin($hex);
531✔
1281
        assert($result !== false);
1282

1283
        return $result;
531✔
1284
    }
1285

1286
    /**
1287
     * @return numeric-string
1288
     */
1289
    #[Override]
1290
    public function toString(): string
1291
    {
1292
        /** @var numeric-string */
1293
        return $this->value;
23,802✔
1294
    }
1295

1296
    /**
1297
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1298
     *
1299
     * @internal
1300
     *
1301
     * @return array{value: string}
1302
     */
1303
    public function __serialize(): array
1304
    {
1305
        return ['value' => $this->value];
6✔
1306
    }
1307

1308
    /**
1309
     * This method is only here to allow unserializing the object and cannot be accessed directly.
1310
     *
1311
     * @internal
1312
     *
1313
     * @param array{value: string} $data
1314
     *
1315
     * @throws LogicException
1316
     */
1317
    public function __unserialize(array $data): void
1318
    {
1319
        /** @phpstan-ignore isset.initializedProperty */
1320
        if (isset($this->value)) {
9✔
1321
            throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
1322
        }
1323

1324
        /** @phpstan-ignore deadCode.unreachable */
1325
        $this->value = $data['value'];
6✔
1326
    }
1327

1328
    #[Override]
1329
    protected static function from(BigNumber $number): static
1330
    {
1331
        return $number->toBigInteger();
24,740✔
1332
    }
1333
}
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