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

brick / math / 21518221648

30 Jan 2026 01:51PM UTC coverage: 99.436% (-0.06%) from 99.491%
21518221648

push

github

BenMorel
Fix misleading docblock

This is a remnant of when RoundingMode was not an enum.

1235 of 1242 relevant lines covered (99.44%)

1110.85 hits per line

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

98.95
/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\Internal\Calculator;
13
use Brick\Math\Internal\CalculatorRegistry;
14
use InvalidArgumentException;
15
use LogicException;
16
use Override;
17

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

37
use const E_USER_DEPRECATED;
38
use const FILTER_VALIDATE_INT;
39

40
/**
41
 * An arbitrary-size integer.
42
 *
43
 * All methods accepting a number as a parameter accept either a BigInteger instance,
44
 * an integer, or a string representing an arbitrary size integer.
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;
19,709✔
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 cannot be empty.');
3✔
91
        }
92

93
        if ($base < 2 || $base > 36) {
2,090✔
94
            throw new InvalidArgumentException(sprintf('Base %d is not in range 2 to 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 cannot 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
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers.
143
     *
144
     * @param string $number   The number to parse.
145
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
146
     *
147
     * @throws NumberFormatException    If the given number is empty or contains invalid chars for the given alphabet.
148
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars.
149
     *
150
     * @pure
151
     */
152
    public static function fromArbitraryBase(string $number, string $alphabet): BigInteger
153
    {
154
        if ($number === '') {
411✔
155
            throw new NumberFormatException('The number cannot be empty.');
3✔
156
        }
157

158
        $base = strlen($alphabet);
408✔
159

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

164
        $pattern = '/[^' . preg_quote($alphabet, '/') . ']/';
402✔
165

166
        if (preg_match($pattern, $number, $matches) === 1) {
402✔
167
            throw NumberFormatException::charNotInAlphabet($matches[0]);
24✔
168
        }
169

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

172
        return new BigInteger($number);
378✔
173
    }
174

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

200
        $twosComplement = false;
1,221✔
201

202
        if ($signed) {
1,221✔
203
            $x = ord($value[0]);
984✔
204

205
            if (($twosComplement = ($x >= 0x80))) {
984✔
206
                $value = ~$value;
906✔
207
            }
208
        }
209

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

212
        if ($twosComplement) {
1,221✔
213
            return $number->plus(1)->negated();
906✔
214
        }
215

216
        return $number;
315✔
217
    }
218

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

237
        if ($numBits === 0) {
162✔
238
            return BigInteger::zero();
3✔
239
        }
240

241
        if ($randomBytesGenerator === null) {
159✔
242
            $randomBytesGenerator = random_bytes(...);
×
243
        }
244

245
        /** @var int<1, max> $byteLength */
246
        $byteLength = intdiv($numBits - 1, 8) + 1;
159✔
247

248
        $extraBits = ($byteLength * 8 - $numBits);
159✔
249
        $bitmask = chr(0xFF >> $extraBits);
159✔
250

251
        $randomBytes = $randomBytesGenerator($byteLength);
159✔
252
        $randomBytes[0] = $randomBytes[0] & $bitmask;
159✔
253

254
        return self::fromBytes($randomBytes, false);
159✔
255
    }
256

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

279
        if ($min->isGreaterThan($max)) {
84✔
280
            throw new MathException('$min cannot be greater than $max.');
3✔
281
        }
282

283
        if ($min->isEqualTo($max)) {
81✔
284
            return $min;
3✔
285
        }
286

287
        $diff = $max->minus($min);
78✔
288
        $bitLength = $diff->getBitLength();
78✔
289

290
        // try until the number is in range (50% to 100% chance of success)
291
        do {
292
            $randomNumber = self::randomBits($bitLength, $randomBytesGenerator);
78✔
293
        } while ($randomNumber->isGreaterThan($diff));
78✔
294

295
        return $randomNumber->plus($min);
78✔
296
    }
297

298
    /**
299
     * Returns a BigInteger representing zero.
300
     *
301
     * @pure
302
     */
303
    public static function zero(): BigInteger
304
    {
305
        /** @var BigInteger|null $zero */
306
        static $zero;
120✔
307

308
        if ($zero === null) {
120✔
309
            $zero = new BigInteger('0');
×
310
        }
311

312
        return $zero;
120✔
313
    }
314

315
    /**
316
     * Returns a BigInteger representing one.
317
     *
318
     * @pure
319
     */
320
    public static function one(): BigInteger
321
    {
322
        /** @var BigInteger|null $one */
323
        static $one;
525✔
324

325
        if ($one === null) {
525✔
326
            $one = new BigInteger('1');
×
327
        }
328

329
        return $one;
525✔
330
    }
331

332
    /**
333
     * Returns a BigInteger representing ten.
334
     *
335
     * @pure
336
     */
337
    public static function ten(): BigInteger
338
    {
339
        /** @var BigInteger|null $ten */
340
        static $ten;
6✔
341

342
        if ($ten === null) {
6✔
343
            $ten = new BigInteger('10');
3✔
344
        }
345

346
        return $ten;
6✔
347
    }
348

349
    /**
350
     * @param BigNumber|int|float|string $a    The first number. Must be convertible to a BigInteger.
351
     * @param BigNumber|int|float|string ...$n The subsequent numbers. Must be convertible to BigInteger.
352
     *
353
     * @pure
354
     */
355
    public static function gcdAll(BigNumber|int|float|string $a, BigNumber|int|float|string ...$n): BigInteger
356
    {
357
        $result = BigInteger::of($a);
1,566✔
358

359
        foreach ($n as $next) {
1,566✔
360
            $result = $result->gcd(BigInteger::of($next));
1,551✔
361

362
            if ($result->isEqualTo(1)) {
1,551✔
363
                return $result;
345✔
364
            }
365
        }
366

367
        return $result;
1,221✔
368
    }
369

370
    /**
371
     * @deprecated Use gcdAll() instead.
372
     *
373
     * @param BigNumber|int|float|string $a    The first number. Must be convertible to a BigInteger.
374
     * @param BigNumber|int|float|string ...$n The subsequent numbers. Must be convertible to BigInteger.
375
     */
376
    public static function gcdMultiple(BigNumber|int|float|string $a, BigNumber|int|float|string ...$n): BigInteger
377
    {
378
        trigger_error(
1,566✔
379
            'BigInteger::gcdMultiple() is deprecated and will be removed in version 0.15. Use gcdAll() instead.',
1,566✔
380
            E_USER_DEPRECATED,
1,566✔
381
        );
1,566✔
382

383
        return self::gcdAll($a, ...$n);
1,566✔
384
    }
385

386
    /**
387
     * Returns the sum of this number and the given one.
388
     *
389
     * @param BigNumber|int|float|string $that The number to add. Must be convertible to a BigInteger.
390
     *
391
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
392
     *
393
     * @pure
394
     */
395
    public function plus(BigNumber|int|float|string $that): BigInteger
396
    {
397
        $that = BigInteger::of($that);
1,629✔
398

399
        if ($that->value === '0') {
1,629✔
400
            return $this;
30✔
401
        }
402

403
        if ($this->value === '0') {
1,599✔
404
            return $that;
72✔
405
        }
406

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

409
        return new BigInteger($value);
1,548✔
410
    }
411

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

425
        if ($that->value === '0') {
990✔
426
            return $this;
30✔
427
        }
428

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

431
        return new BigInteger($value);
969✔
432
    }
433

434
    /**
435
     * Returns the product of this number and the given one.
436
     *
437
     * @param BigNumber|int|float|string $that The multiplier. Must be convertible to a BigInteger.
438
     *
439
     * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigInteger.
440
     *
441
     * @pure
442
     */
443
    public function multipliedBy(BigNumber|int|float|string $that): BigInteger
444
    {
445
        $that = BigInteger::of($that);
1,272✔
446

447
        if ($that->value === '1') {
1,272✔
448
            return $this;
345✔
449
        }
450

451
        if ($this->value === '1') {
1,248✔
452
            return $that;
330✔
453
        }
454

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

457
        return new BigInteger($value);
1,158✔
458
    }
459

460
    /**
461
     * Returns the result of the division of this number by the given one.
462
     *
463
     * @param BigNumber|int|float|string $that         The divisor. Must be convertible to a BigInteger.
464
     * @param RoundingMode               $roundingMode An optional rounding mode, defaults to Unnecessary.
465
     *
466
     * @throws MathException If the divisor is not a valid number, is not convertible to a BigInteger, is zero,
467
     *                       or RoundingMode::Unnecessary is used and the remainder is not zero.
468
     *
469
     * @pure
470
     */
471
    public function dividedBy(BigNumber|int|float|string $that, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
472
    {
473
        $that = BigInteger::of($that);
1,980✔
474

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

479
        if ($that->value === '0') {
1,968✔
480
            throw DivisionByZeroException::divisionByZero();
6✔
481
        }
482

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

485
        return new BigInteger($result);
1,869✔
486
    }
487

488
    /**
489
     * Limits (clamps) this number between the given minimum and maximum values.
490
     *
491
     * If the number is lower than $min, returns a copy of $min.
492
     * If the number is greater than $max, returns a copy of $max.
493
     * Otherwise, returns this number unchanged.
494
     *
495
     * @param BigNumber|int|float|string $min The minimum. Must be convertible to a BigInteger.
496
     * @param BigNumber|int|float|string $max The maximum. Must be convertible to a BigInteger.
497
     *
498
     * @throws MathException            If min/max are not convertible to a BigInteger.
499
     * @throws InvalidArgumentException If min is greater than max.
500
     */
501
    public function clamp(BigNumber|int|float|string $min, BigNumber|int|float|string $max): BigInteger
502
    {
503
        $min = BigInteger::of($min);
33✔
504
        $max = BigInteger::of($max);
33✔
505

506
        if ($min->isGreaterThan($max)) {
33✔
507
            throw new InvalidArgumentException('Minimum value must be less than or equal to maximum value.');
3✔
508
        }
509

510
        if ($this->isLessThan($min)) {
30✔
511
            return $min;
9✔
512
        } elseif ($this->isGreaterThan($max)) {
21✔
513
            return $max;
3✔
514
        }
515

516
        return $this;
18✔
517
    }
518

519
    /**
520
     * Returns this number exponentiated to the given value.
521
     *
522
     * @throws InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
523
     *
524
     * @pure
525
     */
526
    public function power(int $exponent): BigInteger
527
    {
528
        if ($exponent === 0) {
1,851✔
529
            return BigInteger::one();
27✔
530
        }
531

532
        if ($exponent === 1) {
1,824✔
533
            return $this;
204✔
534
        }
535

536
        if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
1,620✔
537
            throw new InvalidArgumentException(sprintf(
6✔
538
                'The exponent %d is not in the range 0 to %d.',
6✔
539
                $exponent,
6✔
540
                Calculator::MAX_POWER,
6✔
541
            ));
6✔
542
        }
543

544
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,614✔
545
    }
546

547
    /**
548
     * Returns the quotient of the division of this number by the given one.
549
     *
550
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
551
     *
552
     * @throws DivisionByZeroException If the divisor is zero.
553
     *
554
     * @pure
555
     */
556
    public function quotient(BigNumber|int|float|string $that): BigInteger
557
    {
558
        $that = BigInteger::of($that);
1,026✔
559

560
        if ($that->value === '1') {
1,026✔
561
            return $this;
75✔
562
        }
563

564
        if ($that->value === '0') {
951✔
565
            throw DivisionByZeroException::divisionByZero();
3✔
566
        }
567

568
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
948✔
569

570
        return new BigInteger($quotient);
948✔
571
    }
572

573
    /**
574
     * Returns the remainder of the division of this number by the given one.
575
     *
576
     * The remainder, when non-zero, has the same sign as the dividend.
577
     *
578
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
579
     *
580
     * @throws DivisionByZeroException If the divisor is zero.
581
     *
582
     * @pure
583
     */
584
    public function remainder(BigNumber|int|float|string $that): BigInteger
585
    {
586
        $that = BigInteger::of($that);
216✔
587

588
        if ($that->value === '1') {
216✔
589
            return BigInteger::zero();
21✔
590
        }
591

592
        if ($that->value === '0') {
195✔
593
            throw DivisionByZeroException::divisionByZero();
3✔
594
        }
595

596
        $remainder = CalculatorRegistry::get()->divR($this->value, $that->value);
192✔
597

598
        return new BigInteger($remainder);
192✔
599
    }
600

601
    /**
602
     * Returns the quotient and remainder of the division of this number by the given one.
603
     *
604
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
605
     *
606
     * @return array{BigInteger, BigInteger} An array containing the quotient and the remainder.
607
     *
608
     * @throws DivisionByZeroException If the divisor is zero.
609
     *
610
     * @pure
611
     */
612
    public function quotientAndRemainder(BigNumber|int|float|string $that): array
613
    {
614
        $that = BigInteger::of($that);
159✔
615

616
        if ($that->value === '0') {
159✔
617
            throw DivisionByZeroException::divisionByZero();
3✔
618
        }
619

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

622
        return [
156✔
623
            new BigInteger($quotient),
156✔
624
            new BigInteger($remainder),
156✔
625
        ];
156✔
626
    }
627

628
    /**
629
     * Returns the modulo of this number and the given one.
630
     *
631
     * The modulo operation yields the same result as the remainder operation when both operands are of the same sign,
632
     * and may differ when signs are different.
633
     *
634
     * The result of the modulo operation, when non-zero, has the same sign as the divisor.
635
     *
636
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
637
     *
638
     * @throws DivisionByZeroException If the divisor is zero.
639
     *
640
     * @pure
641
     */
642
    public function mod(BigNumber|int|float|string $that): BigInteger
643
    {
644
        $that = BigInteger::of($that);
195✔
645

646
        if ($that->value === '0') {
195✔
647
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
648
        }
649

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

652
        return new BigInteger($value);
192✔
653
    }
654

655
    /**
656
     * Returns the modular multiplicative inverse of this BigInteger modulo $m.
657
     *
658
     * @param BigNumber|int|float|string $m The modulus. Must be convertible to a BigInteger.
659
     *
660
     * @throws DivisionByZeroException If $m is zero.
661
     * @throws NegativeNumberException If $m is negative.
662
     * @throws MathException           If this BigInteger has no multiplicative inverse mod m (that is, this BigInteger
663
     *                                 is not relatively prime to m).
664
     *
665
     * @pure
666
     */
667
    public function modInverse(BigNumber|int|float|string $m): BigInteger
668
    {
669
        $m = BigInteger::of($m);
75✔
670

671
        if ($m->value === '0') {
75✔
672
            throw DivisionByZeroException::modulusMustNotBeZero();
6✔
673
        }
674

675
        if ($m->isNegative()) {
69✔
676
            throw new NegativeNumberException('Modulus must not be negative.');
3✔
677
        }
678

679
        if ($m->value === '1') {
66✔
680
            return BigInteger::zero();
3✔
681
        }
682

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

685
        if ($value === null) {
63✔
686
            throw new MathException('Unable to compute the modInverse for the given modulus.');
15✔
687
        }
688

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

692
    /**
693
     * Returns this number raised into power with modulo.
694
     *
695
     * This operation only works on positive numbers.
696
     *
697
     * @param BigNumber|int|float|string $exp The exponent. Must be positive or zero.
698
     * @param BigNumber|int|float|string $mod The modulus. Must be strictly positive.
699
     *
700
     * @throws NegativeNumberException If any of the operands is negative.
701
     * @throws DivisionByZeroException If the modulus is zero.
702
     *
703
     * @pure
704
     */
705
    public function modPow(BigNumber|int|float|string $exp, BigNumber|int|float|string $mod): BigInteger
706
    {
707
        $exp = BigInteger::of($exp);
47✔
708
        $mod = BigInteger::of($mod);
47✔
709

710
        if ($this->isNegative() || $exp->isNegative() || $mod->isNegative()) {
47✔
711
            throw new NegativeNumberException('The operands cannot be negative.');
9✔
712
        }
713

714
        if ($mod->isZero()) {
38✔
715
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
716
        }
717

718
        $result = CalculatorRegistry::get()->modPow($this->value, $exp->value, $mod->value);
35✔
719

720
        return new BigInteger($result);
35✔
721
    }
722

723
    /**
724
     * Returns the greatest common divisor of this number and the given one.
725
     *
726
     * The GCD is always positive, unless both operands are zero, in which case it is zero.
727
     *
728
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
729
     *
730
     * @pure
731
     */
732
    public function gcd(BigNumber|int|float|string $that): BigInteger
733
    {
734
        $that = BigInteger::of($that);
3,201✔
735

736
        if ($that->value === '0' && $this->value[0] !== '-') {
3,201✔
737
            return $this;
60✔
738
        }
739

740
        if ($this->value === '0' && $that->value[0] !== '-') {
3,141✔
741
            return $that;
30✔
742
        }
743

744
        $value = CalculatorRegistry::get()->gcd($this->value, $that->value);
3,111✔
745

746
        return new BigInteger($value);
3,111✔
747
    }
748

749
    /**
750
     * Returns the integer square root number of this number, rounded down.
751
     *
752
     * The result is the largest x such that x² ≤ n.
753
     *
754
     * @throws NegativeNumberException If this number is negative.
755
     *
756
     * @pure
757
     */
758
    public function sqrt(): BigInteger
759
    {
760
        if ($this->value[0] === '-') {
1,008✔
761
            throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
3✔
762
        }
763

764
        $value = CalculatorRegistry::get()->sqrt($this->value);
1,005✔
765

766
        return new BigInteger($value);
1,005✔
767
    }
768

769
    /**
770
     * Returns the absolute value of this number.
771
     *
772
     * @pure
773
     */
774
    public function abs(): BigInteger
775
    {
776
        return $this->isNegative() ? $this->negated() : $this;
678✔
777
    }
778

779
    /**
780
     * Returns the inverse of this number.
781
     *
782
     * @pure
783
     */
784
    public function negated(): BigInteger
785
    {
786
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
2,850✔
787
    }
788

789
    /**
790
     * Returns the integer bitwise-and combined with another integer.
791
     *
792
     * This method returns a negative BigInteger if and only if both operands are negative.
793
     *
794
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
795
     *
796
     * @pure
797
     */
798
    public function and(BigNumber|int|float|string $that): BigInteger
799
    {
800
        $that = BigInteger::of($that);
153✔
801

802
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
803
    }
804

805
    /**
806
     * Returns the integer bitwise-or combined with another integer.
807
     *
808
     * This method returns a negative BigInteger if and only if either of the operands is negative.
809
     *
810
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
811
     *
812
     * @pure
813
     */
814
    public function or(BigNumber|int|float|string $that): BigInteger
815
    {
816
        $that = BigInteger::of($that);
138✔
817

818
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
819
    }
820

821
    /**
822
     * Returns the integer bitwise-xor combined with another integer.
823
     *
824
     * This method returns a negative BigInteger if and only if exactly one of the operands is negative.
825
     *
826
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
827
     *
828
     * @pure
829
     */
830
    public function xor(BigNumber|int|float|string $that): BigInteger
831
    {
832
        $that = BigInteger::of($that);
144✔
833

834
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
835
    }
836

837
    /**
838
     * Returns the bitwise-not of this BigInteger.
839
     *
840
     * @pure
841
     */
842
    public function not(): BigInteger
843
    {
844
        return $this->negated()->minus(1);
57✔
845
    }
846

847
    /**
848
     * Returns the integer left shifted by a given number of bits.
849
     *
850
     * @pure
851
     */
852
    public function shiftedLeft(int $distance): BigInteger
853
    {
854
        if ($distance === 0) {
594✔
855
            return $this;
6✔
856
        }
857

858
        if ($distance < 0) {
588✔
859
            return $this->shiftedRight(-$distance);
198✔
860
        }
861

862
        return $this->multipliedBy(BigInteger::of(2)->power($distance));
390✔
863
    }
864

865
    /**
866
     * Returns the integer right shifted by a given number of bits.
867
     *
868
     * @pure
869
     */
870
    public function shiftedRight(int $distance): BigInteger
871
    {
872
        if ($distance === 0) {
1,518✔
873
            return $this;
66✔
874
        }
875

876
        if ($distance < 0) {
1,452✔
877
            return $this->shiftedLeft(-$distance);
195✔
878
        }
879

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

882
        if ($this->isPositiveOrZero()) {
1,257✔
883
            return $this->quotient($operand);
672✔
884
        }
885

886
        return $this->dividedBy($operand, RoundingMode::Up);
585✔
887
    }
888

889
    /**
890
     * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
891
     *
892
     * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation.
893
     * Computes (ceil(log2(this < 0 ? -this : this+1))).
894
     *
895
     * @pure
896
     */
897
    public function getBitLength(): int
898
    {
899
        if ($this->value === '0') {
321✔
900
            return 0;
12✔
901
        }
902

903
        if ($this->isNegative()) {
315✔
904
            return $this->abs()->minus(1)->getBitLength();
120✔
905
        }
906

907
        return strlen($this->toBase(2));
309✔
908
    }
909

910
    /**
911
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
912
     *
913
     * Returns -1 if this BigInteger contains no one bits.
914
     *
915
     * @pure
916
     */
917
    public function getLowestSetBit(): int
918
    {
919
        $n = $this;
81✔
920
        $bitLength = $this->getBitLength();
81✔
921

922
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
923
            if ($n->isOdd()) {
81✔
924
                return $i;
78✔
925
            }
926

927
            $n = $n->shiftedRight(1);
51✔
928
        }
929

930
        return -1;
3✔
931
    }
932

933
    /**
934
     * Returns whether this number is even.
935
     *
936
     * @pure
937
     */
938
    public function isEven(): bool
939
    {
940
        return in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
941
    }
942

943
    /**
944
     * Returns whether this number is odd.
945
     *
946
     * @pure
947
     */
948
    public function isOdd(): bool
949
    {
950
        return in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
951
    }
952

953
    /**
954
     * Returns true if and only if the designated bit is set.
955
     *
956
     * Computes ((this & (1<<n)) != 0).
957
     *
958
     * @param int $n The bit to test, 0-based.
959
     *
960
     * @throws InvalidArgumentException If the bit to test is negative.
961
     *
962
     * @pure
963
     */
964
    public function testBit(int $n): bool
965
    {
966
        if ($n < 0) {
873✔
967
            throw new InvalidArgumentException('The bit to test cannot be negative.');
3✔
968
        }
969

970
        return $this->shiftedRight($n)->isOdd();
870✔
971
    }
972

973
    #[Override]
974
    public function compareTo(BigNumber|int|float|string $that): int
975
    {
976
        $that = BigNumber::of($that);
2,318✔
977

978
        if ($that instanceof BigInteger) {
2,318✔
979
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,210✔
980
        }
981

982
        return -$that->compareTo($this);
108✔
983
    }
984

985
    #[Override]
986
    public function getSign(): int
987
    {
988
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
3,308✔
989
    }
990

991
    #[Override]
992
    public function toBigInteger(): BigInteger
993
    {
994
        return $this;
13,409✔
995
    }
996

997
    #[Override]
998
    public function toBigDecimal(): BigDecimal
999
    {
1000
        return self::newBigDecimal($this->value);
4,056✔
1001
    }
1002

1003
    #[Override]
1004
    public function toBigRational(): BigRational
1005
    {
1006
        return self::newBigRational($this, BigInteger::one(), false);
468✔
1007
    }
1008

1009
    #[Override]
1010
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
1011
    {
1012
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
1013
    }
1014

1015
    #[Override]
1016
    public function toInt(): int
1017
    {
1018
        $intValue = filter_var($this->value, FILTER_VALIDATE_INT);
87✔
1019

1020
        if ($intValue === false) {
87✔
1021
            throw IntegerOverflowException::toIntOverflow($this);
15✔
1022
        }
1023

1024
        return $intValue;
72✔
1025
    }
1026

1027
    #[Override]
1028
    public function toFloat(): float
1029
    {
1030
        return (float) $this->value;
48✔
1031
    }
1032

1033
    /**
1034
     * Returns a string representation of this number in the given base.
1035
     *
1036
     * The output will always be lowercase for bases greater than 10.
1037
     *
1038
     * @throws InvalidArgumentException If the base is out of range.
1039
     *
1040
     * @pure
1041
     */
1042
    public function toBase(int $base): string
1043
    {
1044
        if ($base === 10) {
1,293✔
1045
            return $this->value;
12✔
1046
        }
1047

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

1052
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,266✔
1053
    }
1054

1055
    /**
1056
     * Returns a string representation of this number in an arbitrary base with a custom alphabet.
1057
     *
1058
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers;
1059
     * a NegativeNumberException will be thrown when attempting to call this method on a negative number.
1060
     *
1061
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
1062
     *
1063
     * @throws NegativeNumberException  If this number is negative.
1064
     * @throws InvalidArgumentException If the given alphabet does not contain at least 2 chars.
1065
     *
1066
     * @pure
1067
     */
1068
    public function toArbitraryBase(string $alphabet): string
1069
    {
1070
        $base = strlen($alphabet);
135✔
1071

1072
        if ($base < 2) {
135✔
1073
            throw new InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
1074
        }
1075

1076
        if ($this->value[0] === '-') {
129✔
1077
            throw new NegativeNumberException(__FUNCTION__ . '() does not support negative numbers.');
3✔
1078
        }
1079

1080
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1081
    }
1082

1083
    /**
1084
     * Returns a string of bytes containing the binary representation of this BigInteger.
1085
     *
1086
     * The string is in big-endian byte-order: the most significant byte is in the zeroth element.
1087
     *
1088
     * If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to
1089
     * the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the
1090
     * number is negative.
1091
     *
1092
     * The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit
1093
     * if `$signed` is true.
1094
     *
1095
     * This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match.
1096
     *
1097
     * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit.
1098
     *
1099
     * @throws NegativeNumberException If $signed is false, and the number is negative.
1100
     *
1101
     * @pure
1102
     */
1103
    public function toBytes(bool $signed = true): string
1104
    {
1105
        if (! $signed && $this->isNegative()) {
534✔
1106
            throw new NegativeNumberException('Cannot convert a negative number to a byte string when $signed is false.');
3✔
1107
        }
1108

1109
        $hex = $this->abs()->toBase(16);
531✔
1110

1111
        if (strlen($hex) % 2 !== 0) {
531✔
1112
            $hex = '0' . $hex;
219✔
1113
        }
1114

1115
        $baseHexLength = strlen($hex);
531✔
1116

1117
        if ($signed) {
531✔
1118
            if ($this->isNegative()) {
492✔
1119
                $bin = hex2bin($hex);
453✔
1120
                assert($bin !== false);
1121

1122
                $hex = bin2hex(~$bin);
453✔
1123
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1124

1125
                $hexLength = strlen($hex);
453✔
1126

1127
                if ($hexLength < $baseHexLength) {
453✔
1128
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1129
                }
1130

1131
                if ($hex[0] < '8') {
453✔
1132
                    $hex = 'FF' . $hex;
114✔
1133
                }
1134
            } else {
1135
                if ($hex[0] >= '8') {
39✔
1136
                    $hex = '00' . $hex;
21✔
1137
                }
1138
            }
1139
        }
1140

1141
        $result = hex2bin($hex);
531✔
1142
        assert($result !== false);
1143

1144
        return $result;
531✔
1145
    }
1146

1147
    /**
1148
     * @return numeric-string
1149
     */
1150
    #[Override]
1151
    public function __toString(): string
1152
    {
1153
        /** @var numeric-string */
1154
        return $this->value;
13,713✔
1155
    }
1156

1157
    /**
1158
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1159
     *
1160
     * @internal
1161
     *
1162
     * @return array{value: string}
1163
     */
1164
    public function __serialize(): array
1165
    {
1166
        return ['value' => $this->value];
6✔
1167
    }
1168

1169
    /**
1170
     * This method is only here to allow unserializing the object and cannot be accessed directly.
1171
     *
1172
     * @internal
1173
     *
1174
     * @param array{value: string} $data
1175
     *
1176
     * @throws LogicException
1177
     */
1178
    public function __unserialize(array $data): void
1179
    {
1180
        /** @phpstan-ignore isset.initializedProperty */
1181
        if (isset($this->value)) {
9✔
1182
            throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
1183
        }
1184

1185
        /** @phpstan-ignore deadCode.unreachable */
1186
        $this->value = $data['value'];
6✔
1187
    }
1188

1189
    #[Override]
1190
    protected static function from(BigNumber $number): static
1191
    {
1192
        return $number->toBigInteger();
13,529✔
1193
    }
1194
}
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