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

brick / math / 21640901425

03 Feb 2026 05:34PM UTC coverage: 99.285% (-0.002%) from 99.287%
21640901425

push

github

BenMorel
Refactor min()/max()/sum() to force at least one parameter

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

3 existing lines in 1 file now uncovered.

1249 of 1258 relevant lines covered (99.28%)

2514.49 hits per line

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

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

3
declare(strict_types=1);
4

5
namespace Brick\Math;
6

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

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

39
use const FILTER_VALIDATE_INT;
40

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

56
    /**
57
     * Protected constructor. Use a factory method to obtain an instance.
58
     *
59
     * @param string $value A string of digits, with optional leading minus sign.
60
     *
61
     * @pure
62
     */
63
    protected function __construct(string $value)
64
    {
65
        $this->value = $value;
31,172✔
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✔
UNCOV
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|string         $min                  The lower bound. Must be convertible to a BigInteger.
267
     * @param BigNumber|int|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|string $min,
277
        BigNumber|int|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 InvalidArgumentException('$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;
222✔
311

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

316
        return $zero;
222✔
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;
525✔
328

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

333
        return $one;
525✔
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|string $a    The first number. Must be convertible to a BigInteger.
355
     * @param BigNumber|int|string ...$n The subsequent numbers. Must be convertible to BigInteger.
356
     *
357
     * @throws MathException If one of the parameters cannot be converted to a BigInteger.
358
     *
359
     * @pure
360
     */
361
    public static function gcdAll(BigNumber|int|string $a, BigNumber|int|string ...$n): BigInteger
362
    {
363
        $result = BigInteger::of($a)->abs();
1,587✔
364

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

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

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

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

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

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

396
        return $result;
273✔
397
    }
398

399
    /**
400
     * Returns the sum of this number and the given one.
401
     *
402
     * @param BigNumber|int|string $that The number to add. Must be convertible to a BigInteger.
403
     *
404
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
405
     *
406
     * @pure
407
     */
408
    public function plus(BigNumber|int|string $that): BigInteger
409
    {
410
        $that = BigInteger::of($that);
1,629✔
411

412
        if ($that->value === '0') {
1,629✔
413
            return $this;
30✔
414
        }
415

416
        if ($this->value === '0') {
1,599✔
417
            return $that;
72✔
418
        }
419

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

422
        return new BigInteger($value);
1,548✔
423
    }
424

425
    /**
426
     * Returns the difference of this number and the given one.
427
     *
428
     * @param BigNumber|int|string $that The number to subtract. Must be convertible to a BigInteger.
429
     *
430
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
431
     *
432
     * @pure
433
     */
434
    public function minus(BigNumber|int|string $that): BigInteger
435
    {
436
        $that = BigInteger::of($that);
990✔
437

438
        if ($that->value === '0') {
990✔
439
            return $this;
30✔
440
        }
441

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

444
        return new BigInteger($value);
969✔
445
    }
446

447
    /**
448
     * Returns the product of this number and the given one.
449
     *
450
     * @param BigNumber|int|string $that The multiplier. Must be convertible to a BigInteger.
451
     *
452
     * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigInteger.
453
     *
454
     * @pure
455
     */
456
    public function multipliedBy(BigNumber|int|string $that): BigInteger
457
    {
458
        $that = BigInteger::of($that);
1,332✔
459

460
        if ($that->value === '1') {
1,332✔
461
            return $this;
417✔
462
        }
463

464
        if ($this->value === '1') {
1,266✔
465
            return $that;
408✔
466
        }
467

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

470
        return new BigInteger($value);
1,158✔
471
    }
472

473
    /**
474
     * Returns the result of the division of this number by the given one.
475
     *
476
     * @param BigNumber|int|string $that         The divisor. Must be convertible to a BigInteger.
477
     * @param RoundingMode         $roundingMode An optional rounding mode, defaults to Unnecessary.
478
     *
479
     * @throws MathException If the divisor is not a valid number, is not convertible to a BigInteger, is zero,
480
     *                       or RoundingMode::Unnecessary is used and the remainder is not zero.
481
     *
482
     * @pure
483
     */
484
    public function dividedBy(BigNumber|int|string $that, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
485
    {
486
        $that = BigInteger::of($that);
1,977✔
487

488
        if ($that->value === '1') {
1,968✔
489
            return $this;
3✔
490
        }
491

492
        if ($that->value === '0') {
1,965✔
493
            throw DivisionByZeroException::divisionByZero();
6✔
494
        }
495

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

498
        return new BigInteger($result);
1,866✔
499
    }
500

501
    /**
502
     * Limits (clamps) this number between the given minimum and maximum values.
503
     *
504
     * If the number is lower than $min, returns a copy of $min.
505
     * If the number is greater than $max, returns a copy of $max.
506
     * Otherwise, returns this number unchanged.
507
     *
508
     * @param BigNumber|int|string $min The minimum. Must be convertible to a BigInteger.
509
     * @param BigNumber|int|string $max The maximum. Must be convertible to a BigInteger.
510
     *
511
     * @throws MathException            If min/max are not convertible to a BigInteger.
512
     * @throws InvalidArgumentException If min is greater than max.
513
     *
514
     * @pure
515
     */
516
    public function clamp(BigNumber|int|string $min, BigNumber|int|string $max): BigInteger
517
    {
518
        $min = BigInteger::of($min);
33✔
519
        $max = BigInteger::of($max);
33✔
520

521
        if ($min->isGreaterThan($max)) {
33✔
522
            throw new InvalidArgumentException('Minimum value must be less than or equal to maximum value.');
3✔
523
        }
524

525
        if ($this->isLessThan($min)) {
30✔
526
            return $min;
9✔
527
        } elseif ($this->isGreaterThan($max)) {
21✔
528
            return $max;
3✔
529
        }
530

531
        return $this;
18✔
532
    }
533

534
    /**
535
     * Returns this number exponentiated to the given value.
536
     *
537
     * @throws InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
538
     *
539
     * @pure
540
     */
541
    public function power(int $exponent): BigInteger
542
    {
543
        if ($exponent === 0) {
1,851✔
544
            return BigInteger::one();
27✔
545
        }
546

547
        if ($exponent === 1) {
1,824✔
548
            return $this;
204✔
549
        }
550

551
        if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
1,620✔
552
            throw new InvalidArgumentException(sprintf(
6✔
553
                'The exponent %d is not in the range 0 to %d.',
6✔
554
                $exponent,
6✔
555
                Calculator::MAX_POWER,
6✔
556
            ));
6✔
557
        }
558

559
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,614✔
560
    }
561

562
    /**
563
     * Returns the quotient of the division of this number by the given one.
564
     *
565
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
566
     *
567
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
568
     * @throws DivisionByZeroException If the divisor is zero.
569
     *
570
     * @pure
571
     */
572
    public function quotient(BigNumber|int|string $that): BigInteger
573
    {
574
        $that = BigInteger::of($that);
2,760✔
575

576
        if ($that->value === '1') {
2,760✔
577
            return $this;
1,413✔
578
        }
579

580
        if ($that->value === '0') {
1,938✔
581
            throw DivisionByZeroException::divisionByZero();
3✔
582
        }
583

584
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
1,935✔
585

586
        return new BigInteger($quotient);
1,935✔
587
    }
588

589
    /**
590
     * Returns the remainder of the division of this number by the given one.
591
     *
592
     * The remainder, when non-zero, has the same sign as the dividend.
593
     *
594
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
595
     *
596
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
597
     * @throws DivisionByZeroException If the divisor is zero.
598
     *
599
     * @pure
600
     */
601
    public function remainder(BigNumber|int|string $that): BigInteger
602
    {
603
        $that = BigInteger::of($that);
273✔
604

605
        if ($that->value === '1') {
273✔
606
            return BigInteger::zero();
24✔
607
        }
608

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

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

615
        return new BigInteger($remainder);
246✔
616
    }
617

618
    /**
619
     * Returns the quotient and remainder of the division of this number by the given one.
620
     *
621
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
622
     *
623
     * @return array{BigInteger, BigInteger} An array containing the quotient and the remainder.
624
     *
625
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
626
     * @throws DivisionByZeroException If the divisor is zero.
627
     *
628
     * @pure
629
     */
630
    public function quotientAndRemainder(BigNumber|int|string $that): array
631
    {
632
        $that = BigInteger::of($that);
147✔
633

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

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

640
        return [
144✔
641
            new BigInteger($quotient),
144✔
642
            new BigInteger($remainder),
144✔
643
        ];
144✔
644
    }
645

646
    /**
647
     * Returns this number modulo the given one.
648
     *
649
     * The result is always non-negative, and is the unique value `r` such that `0 <= r < m`
650
     * and `this - r` is a multiple of `m`.
651
     *
652
     * This is also known as Euclidean modulo. Unlike `remainder()`, which can return negative values
653
     * when the dividend is negative, `mod()` always returns a non-negative result.
654
     *
655
     * Examples:
656
     *
657
     * - `7` mod `3` returns `1`
658
     * - `-7` mod `3` returns `2`
659
     *
660
     * @param BigNumber|int|string $modulus The modulus, strictly positive. Must be convertible to a BigInteger.
661
     *
662
     * @throws MathException           If the modulus is not valid, or is not convertible to a BigInteger.
663
     * @throws DivisionByZeroException If the modulus is zero.
664
     * @throws NegativeNumberException If the modulus is negative.
665
     *
666
     * @pure
667
     */
668
    public function mod(BigNumber|int|string $modulus): BigInteger
669
    {
670
        $modulus = BigInteger::of($modulus);
105✔
671

672
        if ($modulus->isZero()) {
105✔
673
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
674
        }
675

676
        if ($modulus->isNegative()) {
102✔
677
            throw new NegativeNumberException('Modulus must be strictly positive.');
3✔
678
        }
679

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

682
        return new BigInteger($value);
99✔
683
    }
684

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

701
        if ($modulus->isZero()) {
75✔
702
            throw DivisionByZeroException::modulusMustNotBeZero();
6✔
703
        }
704

705
        if ($modulus->isNegative()) {
69✔
706
            throw new NegativeNumberException('Modulus must be strictly positive.');
3✔
707
        }
708

709
        if ($modulus->value === '1') {
66✔
710
            return BigInteger::zero();
3✔
711
        }
712

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

715
        if ($value === null) {
63✔
716
            throw NoInverseException::noModularInverse();
15✔
717
        }
718

719
        return new BigInteger($value);
48✔
720
    }
721

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

741
        if ($exponent->isNegative()) {
185✔
742
            throw new NegativeNumberException('Exponent must not be negative.');
3✔
743
        }
744

745
        if ($modulus->isZero()) {
182✔
746
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
747
        }
748

749
        if ($modulus->isNegative()) {
179✔
750
            throw new NegativeNumberException('Modulus must be strictly positive.');
3✔
751
        }
752

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

755
        return new BigInteger($result);
176✔
756
    }
757

758
    /**
759
     * Returns the greatest common divisor of this number and the given one.
760
     *
761
     * The GCD is always positive, unless both operands are zero, in which case it is zero.
762
     *
763
     * @param BigNumber|int|string $that The operand. Must be convertible to a BigInteger.
764
     *
765
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
766
     *
767
     * @pure
768
     */
769
    public function gcd(BigNumber|int|string $that): BigInteger
770
    {
771
        $that = BigInteger::of($that);
5,013✔
772

773
        if ($that->value === '0' && $this->value[0] !== '-') {
5,013✔
774
            return $this;
66✔
775
        }
776

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

781
        $value = CalculatorRegistry::get()->gcd($this->value, $that->value);
4,851✔
782

783
        return new BigInteger($value);
4,851✔
784
    }
785

786
    /**
787
     * Returns the least common multiple of this number and the given one.
788
     *
789
     * The LCM is always positive, unless at least one operand is zero, in which case it is zero.
790
     *
791
     * @param BigNumber|int|string $that The operand. Must be convertible to a BigInteger.
792
     *
793
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
794
     *
795
     * @pure
796
     */
797
    public function lcm(BigNumber|int|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 of this number, rounded according to the given rounding mode.
812
     *
813
     * @param RoundingMode $roundingMode The rounding mode to use, defaults to Unnecessary.
814
     *
815
     * @throws NegativeNumberException    If this number is negative.
816
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, and the number is not a perfect square.
817
     *
818
     * @pure
819
     */
820
    public function sqrt(RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
821
    {
822
        if ($this->value[0] === '-') {
10,623✔
823
            throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
3✔
824
        }
825

826
        $calculator = CalculatorRegistry::get();
10,620✔
827

828
        $sqrt = $calculator->sqrt($this->value);
10,620✔
829

830
        // For Down and Floor (equivalent for non-negative numbers), return floor sqrt
831
        if ($roundingMode === RoundingMode::Down || $roundingMode === RoundingMode::Floor) {
10,620✔
832
            return new BigInteger($sqrt);
2,130✔
833
        }
834

835
        // Check if the sqrt is exact
836
        $s2 = $calculator->mul($sqrt, $sqrt);
8,490✔
837
        $remainder = $calculator->sub($this->value, $s2);
8,490✔
838

839
        if ($remainder === '0') {
8,490✔
840
            // sqrt is exact
841
            return new BigInteger($sqrt);
5,385✔
842
        }
843

844
        // sqrt is not exact
845
        if ($roundingMode === RoundingMode::Unnecessary) {
3,105✔
846
            throw RoundingNecessaryException::roundingNecessary();
390✔
847
        }
848

849
        // For Up and Ceiling (equivalent for non-negative numbers), round up
850
        if ($roundingMode === RoundingMode::Up || $roundingMode === RoundingMode::Ceiling) {
2,715✔
851
            return new BigInteger($calculator->add($sqrt, '1'));
780✔
852
        }
853

854
        // For Half* modes, compare our number to the midpoint of the interval [s², (s+1)²[.
855
        // The midpoint is s² + s + 0.5. Comparing n >= s² + s + 0.5 with remainder = n − s²
856
        // is equivalent to comparing 2*remainder >= 2*s + 1.
857
        $twoRemainder = $calculator->mul($remainder, '2');
1,935✔
858
        $threshold = $calculator->add($calculator->mul($sqrt, '2'), '1');
1,935✔
859
        $cmp = $calculator->cmp($twoRemainder, $threshold);
1,935✔
860

861
        // We're supposed to increment (round up) when:
862
        //   - HalfUp, HalfCeiling => $cmp >= 0
863
        //   - HalfDown, HalfFloor => $cmp > 0
864
        //   - HalfEven => $cmp > 0 || ($cmp === 0 && $sqrt % 2 === 1)
865
        // But 2*remainder is always even and 2*s + 1 is always odd, so $cmp is never zero.
866
        // Therefore, all Half* modes simplify to:
867
        if ($cmp > 0) {
1,935✔
868
            $sqrt = $calculator->add($sqrt, '1');
990✔
869
        }
870

871
        return new BigInteger($sqrt);
1,935✔
872
    }
873

874
    public function negated(): static
875
    {
876
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
3,750✔
877
    }
878

879
    /**
880
     * Returns the integer bitwise-and combined with another integer.
881
     *
882
     * This method returns a negative BigInteger if and only if both operands are negative.
883
     *
884
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
885
     *
886
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
887
     *
888
     * @pure
889
     */
890
    public function and(BigNumber|int|string $that): BigInteger
891
    {
892
        $that = BigInteger::of($that);
153✔
893

894
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
895
    }
896

897
    /**
898
     * Returns the integer bitwise-or combined with another integer.
899
     *
900
     * This method returns a negative BigInteger if and only if either of the operands is negative.
901
     *
902
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
903
     *
904
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
905
     *
906
     * @pure
907
     */
908
    public function or(BigNumber|int|string $that): BigInteger
909
    {
910
        $that = BigInteger::of($that);
138✔
911

912
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
913
    }
914

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

930
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
931
    }
932

933
    /**
934
     * Returns the bitwise-not of this BigInteger.
935
     *
936
     * @pure
937
     */
938
    public function not(): BigInteger
939
    {
940
        return $this->negated()->minus(1);
57✔
941
    }
942

943
    /**
944
     * Returns the integer left shifted by a given number of bits.
945
     *
946
     * @throws InvalidArgumentException If the number of bits is out of range.
947
     *
948
     * @pure
949
     */
950
    public function shiftedLeft(int $bits): BigInteger
951
    {
952
        if ($bits === 0) {
594✔
953
            return $this;
6✔
954
        }
955

956
        if ($bits < 0) {
588✔
957
            return $this->shiftedRight(-$bits);
198✔
958
        }
959

960
        return $this->multipliedBy(BigInteger::of(2)->power($bits));
390✔
961
    }
962

963
    /**
964
     * Returns the integer right shifted by a given number of bits.
965
     *
966
     * @throws InvalidArgumentException If the number of bits is out of range.
967
     *
968
     * @pure
969
     */
970
    public function shiftedRight(int $bits): BigInteger
971
    {
972
        if ($bits === 0) {
1,518✔
973
            return $this;
66✔
974
        }
975

976
        if ($bits < 0) {
1,452✔
977
            return $this->shiftedLeft(-$bits);
195✔
978
        }
979

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

982
        if ($this->isPositiveOrZero()) {
1,257✔
983
            return $this->quotient($operand);
672✔
984
        }
985

986
        return $this->dividedBy($operand, RoundingMode::Up);
585✔
987
    }
988

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

1003
        if ($this->isNegative()) {
315✔
1004
            return $this->abs()->minus(1)->getBitLength();
120✔
1005
        }
1006

1007
        return strlen($this->toBase(2));
309✔
1008
    }
1009

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

1022
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
1023
            if ($n->isOdd()) {
81✔
1024
                return $i;
78✔
1025
            }
1026

1027
            $n = $n->shiftedRight(1);
51✔
1028
        }
1029

1030
        return -1;
3✔
1031
    }
1032

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

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

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

1070
        return $this->shiftedRight($n)->isOdd();
870✔
1071
    }
1072

1073
    #[Override]
1074
    public function compareTo(BigNumber|int|string $that): int
1075
    {
1076
        $that = BigNumber::of($that);
2,327✔
1077

1078
        if ($that instanceof BigInteger) {
2,327✔
1079
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,219✔
1080
        }
1081

1082
        return -$that->compareTo($this);
108✔
1083
    }
1084

1085
    #[Override]
1086
    public function getSign(): int
1087
    {
1088
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
5,798✔
1089
    }
1090

1091
    #[Override]
1092
    public function toBigInteger(): BigInteger
1093
    {
1094
        return $this;
24,560✔
1095
    }
1096

1097
    #[Override]
1098
    public function toBigDecimal(): BigDecimal
1099
    {
1100
        return self::newBigDecimal($this->value);
5,127✔
1101
    }
1102

1103
    #[Override]
1104
    public function toBigRational(): BigRational
1105
    {
1106
        return self::newBigRational($this, BigInteger::one(), false, false);
483✔
1107
    }
1108

1109
    #[Override]
1110
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
1111
    {
1112
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
1113
    }
1114

1115
    #[Override]
1116
    public function toInt(): int
1117
    {
1118
        $intValue = filter_var($this->value, FILTER_VALIDATE_INT);
87✔
1119

1120
        if ($intValue === false) {
87✔
1121
            throw IntegerOverflowException::toIntOverflow($this);
15✔
1122
        }
1123

1124
        return $intValue;
72✔
1125
    }
1126

1127
    #[Override]
1128
    public function toFloat(): float
1129
    {
1130
        return (float) $this->value;
42✔
1131
    }
1132

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

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

1152
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,266✔
1153
    }
1154

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

1172
        if ($base < 2) {
144✔
1173
            throw new InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
1174
        }
1175

1176
        if (strlen(count_chars($alphabet, 3)) !== $base) {
138✔
1177
            throw new InvalidArgumentException('The alphabet must not contain duplicate chars.');
9✔
1178
        }
1179

1180
        if ($this->value[0] === '-') {
129✔
1181
            throw new NegativeNumberException(__FUNCTION__ . '() does not support negative numbers.');
3✔
1182
        }
1183

1184
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1185
    }
1186

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

1213
        $hex = $this->abs()->toBase(16);
531✔
1214

1215
        if (strlen($hex) % 2 !== 0) {
531✔
1216
            $hex = '0' . $hex;
219✔
1217
        }
1218

1219
        $baseHexLength = strlen($hex);
531✔
1220

1221
        if ($signed) {
531✔
1222
            if ($this->isNegative()) {
492✔
1223
                $bin = hex2bin($hex);
453✔
1224
                assert($bin !== false);
1225

1226
                $hex = bin2hex(~$bin);
453✔
1227
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1228

1229
                $hexLength = strlen($hex);
453✔
1230

1231
                if ($hexLength < $baseHexLength) {
453✔
1232
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1233
                }
1234

1235
                if ($hex[0] < '8') {
453✔
1236
                    $hex = 'FF' . $hex;
114✔
1237
                }
1238
            } else {
1239
                if ($hex[0] >= '8') {
39✔
1240
                    $hex = '00' . $hex;
21✔
1241
                }
1242
            }
1243
        }
1244

1245
        $result = hex2bin($hex);
531✔
1246
        assert($result !== false);
1247

1248
        return $result;
531✔
1249
    }
1250

1251
    /**
1252
     * @return numeric-string
1253
     */
1254
    #[Override]
1255
    public function toString(): string
1256
    {
1257
        /** @var numeric-string */
1258
        return $this->value;
23,703✔
1259
    }
1260

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

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

1289
        /** @phpstan-ignore deadCode.unreachable */
1290
        $this->value = $data['value'];
6✔
1291
    }
1292

1293
    #[Override]
1294
    protected static function from(BigNumber $number): static
1295
    {
1296
        return $number->toBigInteger();
24,698✔
1297
    }
1298
}
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