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

brick / math / 21323300429

24 Jan 2026 12:18AM UTC coverage: 99.426% (-0.3%) from 99.742%
21323300429

push

github

BenMorel
Replace gcdMultiple() with gcdAll()

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

257 existing lines in 4 files now uncovered.

1213 of 1220 relevant lines covered (99.43%)

1123.2 hits per line

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

98.94
/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,688✔
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✔
UNCOV
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;
132✔
307

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

312
        return $zero;
132✔
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✔
UNCOV
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,605✔
398

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

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

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

409
        return new BigInteger($value);
1,527✔
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);
963✔
424

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

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

431
        return new BigInteger($value);
942✔
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,245✔
446

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

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

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

457
        return new BigInteger($value);
1,131✔
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
     */
500
    public function clamp(BigNumber|int|float|string $min, BigNumber|int|float|string $max): BigInteger
501
    {
502
        if ($this->isLessThan($min)) {
30✔
503
            return BigInteger::of($min);
9✔
504
        } elseif ($this->isGreaterThan($max)) {
21✔
505
            return BigInteger::of($max);
3✔
506
        }
507

508
        return $this;
18✔
509
    }
510

511
    /**
512
     * Returns this number exponentiated to the given value.
513
     *
514
     * @throws InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
515
     *
516
     * @pure
517
     */
518
    public function power(int $exponent): BigInteger
519
    {
520
        if ($exponent === 0) {
1,851✔
521
            return BigInteger::one();
27✔
522
        }
523

524
        if ($exponent === 1) {
1,824✔
525
            return $this;
204✔
526
        }
527

528
        if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
1,620✔
529
            throw new InvalidArgumentException(sprintf(
6✔
530
                'The exponent %d is not in the range 0 to %d.',
6✔
531
                $exponent,
6✔
532
                Calculator::MAX_POWER,
6✔
533
            ));
6✔
534
        }
535

536
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,614✔
537
    }
538

539
    /**
540
     * Returns the quotient of the division of this number by the given one.
541
     *
542
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
543
     *
544
     * @throws DivisionByZeroException If the divisor is zero.
545
     *
546
     * @pure
547
     */
548
    public function quotient(BigNumber|int|float|string $that): BigInteger
549
    {
550
        $that = BigInteger::of($that);
1,047✔
551

552
        if ($that->value === '1') {
1,047✔
553
            return $this;
87✔
554
        }
555

556
        if ($that->value === '0') {
960✔
557
            throw DivisionByZeroException::divisionByZero();
3✔
558
        }
559

560
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
957✔
561

562
        return new BigInteger($quotient);
957✔
563
    }
564

565
    /**
566
     * Returns the remainder of the division of this number by the given one.
567
     *
568
     * The remainder, when non-zero, has the same sign as the dividend.
569
     *
570
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
571
     *
572
     * @throws DivisionByZeroException If the divisor is zero.
573
     *
574
     * @pure
575
     */
576
    public function remainder(BigNumber|int|float|string $that): BigInteger
577
    {
578
        $that = BigInteger::of($that);
240✔
579

580
        if ($that->value === '1') {
240✔
581
            return BigInteger::zero();
33✔
582
        }
583

584
        if ($that->value === '0') {
207✔
585
            throw DivisionByZeroException::divisionByZero();
3✔
586
        }
587

588
        $remainder = CalculatorRegistry::get()->divR($this->value, $that->value);
204✔
589

590
        return new BigInteger($remainder);
204✔
591
    }
592

593
    /**
594
     * Returns the quotient and remainder of the division of this number by the given one.
595
     *
596
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
597
     *
598
     * @return array{BigInteger, BigInteger} An array containing the quotient and the remainder.
599
     *
600
     * @throws DivisionByZeroException If the divisor is zero.
601
     *
602
     * @pure
603
     */
604
    public function quotientAndRemainder(BigNumber|int|float|string $that): array
605
    {
606
        $that = BigInteger::of($that);
159✔
607

608
        if ($that->value === '0') {
159✔
609
            throw DivisionByZeroException::divisionByZero();
3✔
610
        }
611

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

614
        return [
156✔
615
            new BigInteger($quotient),
156✔
616
            new BigInteger($remainder),
156✔
617
        ];
156✔
618
    }
619

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

638
        if ($that->value === '0') {
195✔
639
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
640
        }
641

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

644
        return new BigInteger($value);
192✔
645
    }
646

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

663
        if ($m->value === '0') {
75✔
664
            throw DivisionByZeroException::modulusMustNotBeZero();
6✔
665
        }
666

667
        if ($m->isNegative()) {
69✔
668
            throw new NegativeNumberException('Modulus must not be negative.');
3✔
669
        }
670

671
        if ($m->value === '1') {
66✔
672
            return BigInteger::zero();
3✔
673
        }
674

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

677
        if ($value === null) {
63✔
678
            throw new MathException('Unable to compute the modInverse for the given modulus.');
15✔
679
        }
680

681
        return new BigInteger($value);
48✔
682
    }
683

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

702
        if ($this->isNegative() || $exp->isNegative() || $mod->isNegative()) {
47✔
703
            throw new NegativeNumberException('The operands cannot be negative.');
9✔
704
        }
705

706
        if ($mod->isZero()) {
38✔
707
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
708
        }
709

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

712
        return new BigInteger($result);
35✔
713
    }
714

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

728
        if ($that->value === '0' && $this->value[0] !== '-') {
3,201✔
729
            return $this;
60✔
730
        }
731

732
        if ($this->value === '0' && $that->value[0] !== '-') {
3,141✔
733
            return $that;
30✔
734
        }
735

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

738
        return new BigInteger($value);
3,111✔
739
    }
740

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

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

758
        return new BigInteger($value);
1,005✔
759
    }
760

761
    /**
762
     * Returns the absolute value of this number.
763
     *
764
     * @pure
765
     */
766
    public function abs(): BigInteger
767
    {
768
        return $this->isNegative() ? $this->negated() : $this;
678✔
769
    }
770

771
    /**
772
     * Returns the inverse of this number.
773
     *
774
     * @pure
775
     */
776
    public function negated(): BigInteger
777
    {
778
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
2,847✔
779
    }
780

781
    /**
782
     * Returns the integer bitwise-and combined with another integer.
783
     *
784
     * This method returns a negative BigInteger if and only if both operands are negative.
785
     *
786
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
787
     *
788
     * @pure
789
     */
790
    public function and(BigNumber|int|float|string $that): BigInteger
791
    {
792
        $that = BigInteger::of($that);
153✔
793

794
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
795
    }
796

797
    /**
798
     * Returns the integer bitwise-or combined with another integer.
799
     *
800
     * This method returns a negative BigInteger if and only if either of the operands is negative.
801
     *
802
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
803
     *
804
     * @pure
805
     */
806
    public function or(BigNumber|int|float|string $that): BigInteger
807
    {
808
        $that = BigInteger::of($that);
138✔
809

810
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
811
    }
812

813
    /**
814
     * Returns the integer bitwise-xor combined with another integer.
815
     *
816
     * This method returns a negative BigInteger if and only if exactly one of the operands is negative.
817
     *
818
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
819
     *
820
     * @pure
821
     */
822
    public function xor(BigNumber|int|float|string $that): BigInteger
823
    {
824
        $that = BigInteger::of($that);
144✔
825

826
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
827
    }
828

829
    /**
830
     * Returns the bitwise-not of this BigInteger.
831
     *
832
     * @pure
833
     */
834
    public function not(): BigInteger
835
    {
836
        return $this->negated()->minus(1);
57✔
837
    }
838

839
    /**
840
     * Returns the integer left shifted by a given number of bits.
841
     *
842
     * @pure
843
     */
844
    public function shiftedLeft(int $distance): BigInteger
845
    {
846
        if ($distance === 0) {
594✔
847
            return $this;
6✔
848
        }
849

850
        if ($distance < 0) {
588✔
851
            return $this->shiftedRight(-$distance);
198✔
852
        }
853

854
        return $this->multipliedBy(BigInteger::of(2)->power($distance));
390✔
855
    }
856

857
    /**
858
     * Returns the integer right shifted by a given number of bits.
859
     *
860
     * @pure
861
     */
862
    public function shiftedRight(int $distance): BigInteger
863
    {
864
        if ($distance === 0) {
1,518✔
865
            return $this;
66✔
866
        }
867

868
        if ($distance < 0) {
1,452✔
869
            return $this->shiftedLeft(-$distance);
195✔
870
        }
871

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

874
        if ($this->isPositiveOrZero()) {
1,257✔
875
            return $this->quotient($operand);
672✔
876
        }
877

878
        return $this->dividedBy($operand, RoundingMode::Up);
585✔
879
    }
880

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

895
        if ($this->isNegative()) {
315✔
896
            return $this->abs()->minus(1)->getBitLength();
120✔
897
        }
898

899
        return strlen($this->toBase(2));
309✔
900
    }
901

902
    /**
903
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
904
     *
905
     * Returns -1 if this BigInteger contains no one bits.
906
     *
907
     * @pure
908
     */
909
    public function getLowestSetBit(): int
910
    {
911
        $n = $this;
81✔
912
        $bitLength = $this->getBitLength();
81✔
913

914
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
915
            if ($n->isOdd()) {
81✔
916
                return $i;
78✔
917
            }
918

919
            $n = $n->shiftedRight(1);
51✔
920
        }
921

922
        return -1;
3✔
923
    }
924

925
    /**
926
     * Returns whether this number is even.
927
     *
928
     * @pure
929
     */
930
    public function isEven(): bool
931
    {
932
        return in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
933
    }
934

935
    /**
936
     * Returns whether this number is odd.
937
     *
938
     * @pure
939
     */
940
    public function isOdd(): bool
941
    {
942
        return in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
943
    }
944

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

962
        return $this->shiftedRight($n)->isOdd();
870✔
963
    }
964

965
    #[Override]
966
    public function compareTo(BigNumber|int|float|string $that): int
967
    {
968
        $that = BigNumber::of($that);
2,315✔
969

970
        if ($that instanceof BigInteger) {
2,315✔
971
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,207✔
972
        }
973

974
        return -$that->compareTo($this);
108✔
975
    }
976

977
    #[Override]
978
    public function getSign(): int
979
    {
980
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
3,275✔
981
    }
982

983
    #[Override]
984
    public function toBigInteger(): BigInteger
985
    {
986
        return $this;
13,466✔
987
    }
988

989
    #[Override]
990
    public function toBigDecimal(): BigDecimal
991
    {
992
        return self::newBigDecimal($this->value);
3,978✔
993
    }
994

995
    #[Override]
996
    public function toBigRational(): BigRational
997
    {
998
        return self::newBigRational($this, BigInteger::one(), false);
468✔
999
    }
1000

1001
    #[Override]
1002
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
1003
    {
1004
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
1005
    }
1006

1007
    #[Override]
1008
    public function toInt(): int
1009
    {
1010
        $intValue = filter_var($this->value, FILTER_VALIDATE_INT);
87✔
1011

1012
        if ($intValue === false) {
87✔
1013
            throw IntegerOverflowException::toIntOverflow($this);
15✔
1014
        }
1015

1016
        return $intValue;
72✔
1017
    }
1018

1019
    #[Override]
1020
    public function toFloat(): float
1021
    {
1022
        return (float) $this->value;
48✔
1023
    }
1024

1025
    /**
1026
     * Returns a string representation of this number in the given base.
1027
     *
1028
     * The output will always be lowercase for bases greater than 10.
1029
     *
1030
     * @throws InvalidArgumentException If the base is out of range.
1031
     *
1032
     * @pure
1033
     */
1034
    public function toBase(int $base): string
1035
    {
1036
        if ($base === 10) {
1,293✔
1037
            return $this->value;
12✔
1038
        }
1039

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

1044
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,266✔
1045
    }
1046

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

1064
        if ($base < 2) {
135✔
1065
            throw new InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
1066
        }
1067

1068
        if ($this->value[0] === '-') {
129✔
1069
            throw new NegativeNumberException(__FUNCTION__ . '() does not support negative numbers.');
3✔
1070
        }
1071

1072
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1073
    }
1074

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

1101
        $hex = $this->abs()->toBase(16);
531✔
1102

1103
        if (strlen($hex) % 2 !== 0) {
531✔
1104
            $hex = '0' . $hex;
219✔
1105
        }
1106

1107
        $baseHexLength = strlen($hex);
531✔
1108

1109
        if ($signed) {
531✔
1110
            if ($this->isNegative()) {
492✔
1111
                $bin = hex2bin($hex);
453✔
1112
                assert($bin !== false);
1113

1114
                $hex = bin2hex(~$bin);
453✔
1115
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1116

1117
                $hexLength = strlen($hex);
453✔
1118

1119
                if ($hexLength < $baseHexLength) {
453✔
1120
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1121
                }
1122

1123
                if ($hex[0] < '8') {
453✔
1124
                    $hex = 'FF' . $hex;
114✔
1125
                }
1126
            } else {
1127
                if ($hex[0] >= '8') {
39✔
1128
                    $hex = '00' . $hex;
21✔
1129
                }
1130
            }
1131
        }
1132

1133
        $result = hex2bin($hex);
531✔
1134
        assert($result !== false);
1135

1136
        return $result;
531✔
1137
    }
1138

1139
    /**
1140
     * @return numeric-string
1141
     */
1142
    #[Override]
1143
    public function __toString(): string
1144
    {
1145
        /** @var numeric-string */
1146
        return $this->value;
13,746✔
1147
    }
1148

1149
    /**
1150
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1151
     *
1152
     * @internal
1153
     *
1154
     * @return array{value: string}
1155
     */
1156
    public function __serialize(): array
1157
    {
1158
        return ['value' => $this->value];
6✔
1159
    }
1160

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

1177
        /** @phpstan-ignore deadCode.unreachable */
1178
        $this->value = $data['value'];
6✔
1179
    }
1180

1181
    #[Override]
1182
    protected static function from(BigNumber $number): static
1183
    {
1184
        return $number->toBigInteger();
13,586✔
1185
    }
1186
}
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