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

brick / math / 21636308270

03 Feb 2026 03:21PM UTC coverage: 99.308% (+0.001%) from 99.307%
21636308270

push

github

BenMorel
Improve & harmonize BigNumber docblocks

1292 of 1301 relevant lines covered (99.31%)

1101.24 hits per line

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

99.02
/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 count_chars;
22
use function filter_var;
23
use function hex2bin;
24
use function in_array;
25
use function intdiv;
26
use function ltrim;
27
use function ord;
28
use function preg_match;
29
use function preg_quote;
30
use function random_bytes;
31
use function sprintf;
32
use function str_repeat;
33
use function strlen;
34
use function strtolower;
35
use function substr;
36
use function trigger_error;
37

38
use const E_USER_DEPRECATED;
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;
20,540✔
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 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 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
     * 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, or contains duplicates.
149
     *
150
     * @pure
151
     */
152
    public static function fromArbitraryBase(string $number, string $alphabet): BigInteger
153
    {
154
        if ($number === '') {
423✔
155
            throw new NumberFormatException('The number must not be empty.');
3✔
156
        }
157

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

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

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

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

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

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

176
        return new BigInteger($number);
378✔
177
    }
178

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

204
        $twosComplement = false;
1,221✔
205

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

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

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

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

220
        return $number;
315✔
221
    }
222

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

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

245
        if ($randomBytesGenerator === null) {
159✔
246
            $randomBytesGenerator = random_bytes(...);
×
247
        }
248

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

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

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

258
        return self::fromBytes($randomBytes, false);
159✔
259
    }
260

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

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

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

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

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

299
        return $randomNumber->plus($min);
78✔
300
    }
301

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

312
        if ($zero === null) {
219✔
313
            $zero = new BigInteger('0');
×
314
        }
315

316
        return $zero;
219✔
317
    }
318

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

329
        if ($one === null) {
528✔
330
            $one = new BigInteger('1');
×
331
        }
332

333
        return $one;
528✔
334
    }
335

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

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

350
        return $ten;
6✔
351
    }
352

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

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

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

371
        return $result;
1,242✔
372
    }
373

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

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

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

392
        return $result;
273✔
393
    }
394

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

482
        return new BigInteger($value);
1,206✔
483
    }
484

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

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

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

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

510
        return new BigInteger($result);
1,869✔
511
    }
512

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

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

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

543
        return $this;
18✔
544
    }
545

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

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

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

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

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

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

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

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

597
        return new BigInteger($quotient);
1,017✔
598
    }
599

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

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

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

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

625
        return new BigInteger($remainder);
261✔
626
    }
627

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

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

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

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

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

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

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

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

687
        return new BigInteger($value);
192✔
688
    }
689

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

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

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

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

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

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

724
        return new BigInteger($value);
48✔
725
    }
726

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

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

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

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

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

759
        return new BigInteger($result);
176✔
760
    }
761

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

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

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

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

785
        return new BigInteger($value);
3,114✔
786
    }
787

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

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

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

807
        return new BigInteger($value);
462✔
808
    }
809

810
    /**
811
     * Returns the integer square root number of this number, rounded down.
812
     *
813
     * The result is the largest x such that x² ≤ n.
814
     *
815
     * @throws NegativeNumberException If this number is negative.
816
     *
817
     * @pure
818
     */
819
    public function sqrt(): BigInteger
820
    {
821
        if ($this->value[0] === '-') {
1,008✔
822
            throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
3✔
823
        }
824

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

827
        return new BigInteger($value);
1,005✔
828
    }
829

830
    public function negated(): static
831
    {
832
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
3,750✔
833
    }
834

835
    /**
836
     * Returns the integer bitwise-and combined with another integer.
837
     *
838
     * This method returns a negative BigInteger if and only if both operands are negative.
839
     *
840
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
841
     *
842
     * @pure
843
     */
844
    public function and(BigNumber|int|float|string $that): BigInteger
845
    {
846
        $that = BigInteger::of($that);
153✔
847

848
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
849
    }
850

851
    /**
852
     * Returns the integer bitwise-or combined with another integer.
853
     *
854
     * This method returns a negative BigInteger if and only if either of the operands is negative.
855
     *
856
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
857
     *
858
     * @pure
859
     */
860
    public function or(BigNumber|int|float|string $that): BigInteger
861
    {
862
        $that = BigInteger::of($that);
138✔
863

864
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
865
    }
866

867
    /**
868
     * Returns the integer bitwise-xor combined with another integer.
869
     *
870
     * This method returns a negative BigInteger if and only if exactly one of the operands is negative.
871
     *
872
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
873
     *
874
     * @pure
875
     */
876
    public function xor(BigNumber|int|float|string $that): BigInteger
877
    {
878
        $that = BigInteger::of($that);
144✔
879

880
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
881
    }
882

883
    /**
884
     * Returns the bitwise-not of this BigInteger.
885
     *
886
     * @pure
887
     */
888
    public function not(): BigInteger
889
    {
890
        return $this->negated()->minus(1);
57✔
891
    }
892

893
    /**
894
     * Returns the integer left shifted by a given number of bits.
895
     *
896
     * @pure
897
     */
898
    public function shiftedLeft(int $distance): BigInteger
899
    {
900
        if ($distance === 0) {
594✔
901
            return $this;
6✔
902
        }
903

904
        if ($distance < 0) {
588✔
905
            return $this->shiftedRight(-$distance);
198✔
906
        }
907

908
        return $this->multipliedBy(BigInteger::of(2)->power($distance));
390✔
909
    }
910

911
    /**
912
     * Returns the integer right shifted by a given number of bits.
913
     *
914
     * @pure
915
     */
916
    public function shiftedRight(int $distance): BigInteger
917
    {
918
        if ($distance === 0) {
1,518✔
919
            return $this;
66✔
920
        }
921

922
        if ($distance < 0) {
1,452✔
923
            return $this->shiftedLeft(-$distance);
195✔
924
        }
925

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

928
        if ($this->isPositiveOrZero()) {
1,257✔
929
            return $this->quotient($operand);
672✔
930
        }
931

932
        return $this->dividedBy($operand, RoundingMode::Up);
585✔
933
    }
934

935
    /**
936
     * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
937
     *
938
     * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation.
939
     * Computes (ceil(log2(this < 0 ? -this : this+1))).
940
     *
941
     * @pure
942
     */
943
    public function getBitLength(): int
944
    {
945
        if ($this->value === '0') {
321✔
946
            return 0;
12✔
947
        }
948

949
        if ($this->isNegative()) {
315✔
950
            return $this->abs()->minus(1)->getBitLength();
120✔
951
        }
952

953
        return strlen($this->toBase(2));
309✔
954
    }
955

956
    /**
957
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
958
     *
959
     * Returns -1 if this BigInteger contains no one bits.
960
     *
961
     * @pure
962
     */
963
    public function getLowestSetBit(): int
964
    {
965
        $n = $this;
81✔
966
        $bitLength = $this->getBitLength();
81✔
967

968
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
969
            if ($n->isOdd()) {
81✔
970
                return $i;
78✔
971
            }
972

973
            $n = $n->shiftedRight(1);
51✔
974
        }
975

976
        return -1;
3✔
977
    }
978

979
    /**
980
     * Returns whether this number is even.
981
     *
982
     * @pure
983
     */
984
    public function isEven(): bool
985
    {
986
        return in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
987
    }
988

989
    /**
990
     * Returns whether this number is odd.
991
     *
992
     * @pure
993
     */
994
    public function isOdd(): bool
995
    {
996
        return in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
997
    }
998

999
    /**
1000
     * Returns true if and only if the designated bit is set.
1001
     *
1002
     * Computes ((this & (1<<n)) != 0).
1003
     *
1004
     * @param int $n The bit to test, 0-based.
1005
     *
1006
     * @throws InvalidArgumentException If the bit to test is negative.
1007
     *
1008
     * @pure
1009
     */
1010
    public function testBit(int $n): bool
1011
    {
1012
        if ($n < 0) {
873✔
1013
            throw new InvalidArgumentException('The bit to test cannot be negative.');
3✔
1014
        }
1015

1016
        return $this->shiftedRight($n)->isOdd();
870✔
1017
    }
1018

1019
    #[Override]
1020
    public function compareTo(BigNumber|int|float|string $that): int
1021
    {
1022
        $that = BigNumber::of($that);
2,327✔
1023

1024
        if ($that instanceof BigInteger) {
2,327✔
1025
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,219✔
1026
        }
1027

1028
        return -$that->compareTo($this);
108✔
1029
    }
1030

1031
    #[Override]
1032
    public function getSign(): int
1033
    {
1034
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
5,891✔
1035
    }
1036

1037
    #[Override]
1038
    public function toBigInteger(): BigInteger
1039
    {
1040
        return $this;
14,237✔
1041
    }
1042

1043
    #[Override]
1044
    public function toBigDecimal(): BigDecimal
1045
    {
1046
        return self::newBigDecimal($this->value);
4,056✔
1047
    }
1048

1049
    #[Override]
1050
    public function toBigRational(): BigRational
1051
    {
1052
        return self::newBigRational($this, BigInteger::one(), false);
471✔
1053
    }
1054

1055
    #[Override]
1056
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
1057
    {
1058
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
1059
    }
1060

1061
    #[Override]
1062
    public function toInt(): int
1063
    {
1064
        $intValue = filter_var($this->value, FILTER_VALIDATE_INT);
87✔
1065

1066
        if ($intValue === false) {
87✔
1067
            throw IntegerOverflowException::toIntOverflow($this);
15✔
1068
        }
1069

1070
        return $intValue;
72✔
1071
    }
1072

1073
    #[Override]
1074
    public function toFloat(): float
1075
    {
1076
        return (float) $this->value;
48✔
1077
    }
1078

1079
    /**
1080
     * Returns a string representation of this number in the given base.
1081
     *
1082
     * The output will always be lowercase for bases greater than 10.
1083
     *
1084
     * @throws InvalidArgumentException If the base is out of range.
1085
     *
1086
     * @pure
1087
     */
1088
    public function toBase(int $base): string
1089
    {
1090
        if ($base === 10) {
1,293✔
1091
            return $this->value;
12✔
1092
        }
1093

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

1098
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,266✔
1099
    }
1100

1101
    /**
1102
     * Returns a string representation of this number in an arbitrary base with a custom alphabet.
1103
     *
1104
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers;
1105
     * a NegativeNumberException will be thrown when attempting to call this method on a negative number.
1106
     *
1107
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
1108
     *
1109
     * @throws NegativeNumberException  If this number is negative.
1110
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars, or contains duplicates.
1111
     *
1112
     * @pure
1113
     */
1114
    public function toArbitraryBase(string $alphabet): string
1115
    {
1116
        $base = strlen($alphabet);
144✔
1117

1118
        if ($base < 2) {
144✔
1119
            throw new InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
1120
        }
1121

1122
        if (strlen(count_chars($alphabet, 3)) !== $base) {
138✔
1123
            throw new InvalidArgumentException('The alphabet must not contain duplicate chars.');
9✔
1124
        }
1125

1126
        if ($this->value[0] === '-') {
129✔
1127
            throw new NegativeNumberException(__FUNCTION__ . '() does not support negative numbers.');
3✔
1128
        }
1129

1130
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1131
    }
1132

1133
    /**
1134
     * Returns a string of bytes containing the binary representation of this BigInteger.
1135
     *
1136
     * The string is in big-endian byte-order: the most significant byte is in the zeroth element.
1137
     *
1138
     * If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to
1139
     * the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the
1140
     * number is negative.
1141
     *
1142
     * The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit
1143
     * if `$signed` is true.
1144
     *
1145
     * This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match.
1146
     *
1147
     * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit.
1148
     *
1149
     * @throws NegativeNumberException If $signed is false, and the number is negative.
1150
     *
1151
     * @pure
1152
     */
1153
    public function toBytes(bool $signed = true): string
1154
    {
1155
        if (! $signed && $this->isNegative()) {
534✔
1156
            throw new NegativeNumberException('Cannot convert a negative number to a byte string when $signed is false.');
3✔
1157
        }
1158

1159
        $hex = $this->abs()->toBase(16);
531✔
1160

1161
        if (strlen($hex) % 2 !== 0) {
531✔
1162
            $hex = '0' . $hex;
219✔
1163
        }
1164

1165
        $baseHexLength = strlen($hex);
531✔
1166

1167
        if ($signed) {
531✔
1168
            if ($this->isNegative()) {
492✔
1169
                $bin = hex2bin($hex);
453✔
1170
                assert($bin !== false);
1171

1172
                $hex = bin2hex(~$bin);
453✔
1173
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1174

1175
                $hexLength = strlen($hex);
453✔
1176

1177
                if ($hexLength < $baseHexLength) {
453✔
1178
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1179
                }
1180

1181
                if ($hex[0] < '8') {
453✔
1182
                    $hex = 'FF' . $hex;
114✔
1183
                }
1184
            } else {
1185
                if ($hex[0] >= '8') {
39✔
1186
                    $hex = '00' . $hex;
21✔
1187
                }
1188
            }
1189
        }
1190

1191
        $result = hex2bin($hex);
531✔
1192
        assert($result !== false);
1193

1194
        return $result;
531✔
1195
    }
1196

1197
    /**
1198
     * @return numeric-string
1199
     */
1200
    #[Override]
1201
    public function __toString(): string
1202
    {
1203
        /** @var numeric-string */
1204
        return $this->value;
14,532✔
1205
    }
1206

1207
    /**
1208
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1209
     *
1210
     * @internal
1211
     *
1212
     * @return array{value: string}
1213
     */
1214
    public function __serialize(): array
1215
    {
1216
        return ['value' => $this->value];
6✔
1217
    }
1218

1219
    /**
1220
     * This method is only here to allow unserializing the object and cannot be accessed directly.
1221
     *
1222
     * @internal
1223
     *
1224
     * @param array{value: string} $data
1225
     *
1226
     * @throws LogicException
1227
     */
1228
    public function __unserialize(array $data): void
1229
    {
1230
        /** @phpstan-ignore isset.initializedProperty */
1231
        if (isset($this->value)) {
9✔
1232
            throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
1233
        }
1234

1235
        /** @phpstan-ignore deadCode.unreachable */
1236
        $this->value = $data['value'];
6✔
1237
    }
1238

1239
    #[Override]
1240
    protected static function from(BigNumber $number): static
1241
    {
1242
        return $number->toBigInteger();
14,357✔
1243
    }
1244
}
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