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

brick / math / 17157350650

22 Aug 2025 02:00PM UTC coverage: 99.739% (-0.001%) from 99.74%
17157350650

push

github

BenMorel
Refactor BigNumber::sum() using getTypePriority()

12 of 12 new or added lines in 4 files covered. (100.0%)

85 existing lines in 3 files now uncovered.

1148 of 1151 relevant lines covered (99.74%)

1145.39 hits per line

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

99.26
/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 Override;
15

16
/**
17
 * An arbitrary-size integer.
18
 *
19
 * All methods accepting a number as a parameter accept either a BigInteger instance,
20
 * an integer, or a string representing an arbitrary size integer.
21
 *
22
 * @psalm-immutable
23
 */
24
final readonly class BigInteger extends BigNumber
25
{
26
    /**
27
     * The value, as a string of digits with optional leading minus sign.
28
     *
29
     * No leading zeros must be present.
30
     * No leading minus sign must be present if the number is zero.
31
     */
32
    private string $value;
33

34
    /**
35
     * Protected constructor. Use a factory method to obtain an instance.
36
     *
37
     * @param string $value A string of digits, with optional leading minus sign.
38
     *
39
     * @pure
40
     */
41
    protected function __construct(string $value)
42
    {
43
        $this->value = $value;
18,833✔
44
    }
45

46
    #[Override]
47
    protected static function from(BigNumber $number): static
48
    {
49
        return $number->toBigInteger();
13,154✔
50
    }
51

52
    #[Override]
53
    protected static function getTypePriority(): int
54
    {
55
        return 1;
57✔
56
    }
57

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

83
        if ($base < 2 || $base > 36) {
2,090✔
84
            throw new \InvalidArgumentException(\sprintf('Base %d is not in range 2 to 36.', $base));
15✔
85
        }
86

87
        if ($number[0] === '-') {
2,075✔
88
            $sign = '-';
27✔
89
            $number = \substr($number, 1);
27✔
90
        } elseif ($number[0] === '+') {
2,048✔
91
            $sign = '';
27✔
92
            $number = \substr($number, 1);
27✔
93
        } else {
94
            $sign = '';
2,021✔
95
        }
96

97
        if ($number === '') {
2,075✔
98
            throw new NumberFormatException('The number cannot be empty.');
6✔
99
        }
100

101
        $number = \ltrim($number, '0');
2,069✔
102

103
        if ($number === '') {
2,069✔
104
            // The result will be the same in any base, avoid further calculation.
105
            return BigInteger::zero();
84✔
106
        }
107

108
        if ($number === '1') {
1,988✔
109
            // The result will be the same in any base, avoid further calculation.
110
            return new BigInteger($sign . '1');
75✔
111
        }
112

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

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

119
        if ($base === 10) {
1,805✔
120
            // The number is usable as is, avoid further calculation.
121
            return new BigInteger($sign . $number);
24✔
122
        }
123

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

126
        return new BigInteger($sign . $result);
1,781✔
127
    }
128

129
    /**
130
     * Parses a string containing an integer in an arbitrary base, using a custom alphabet.
131
     *
132
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers.
133
     *
134
     * @pure
135
     *
136
     * @param string $number   The number to parse.
137
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
138
     *
139
     * @throws NumberFormatException     If the given number is empty or contains invalid chars for the given alphabet.
140
     * @throws \InvalidArgumentException If the alphabet does not contain at least 2 chars.
141
     */
142
    public static function fromArbitraryBase(string $number, string $alphabet) : BigInteger
143
    {
144
        if ($number === '') {
411✔
145
            throw new NumberFormatException('The number cannot be empty.');
3✔
146
        }
147

148
        $base = \strlen($alphabet);
408✔
149

150
        if ($base < 2) {
408✔
151
            throw new \InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
152
        }
153

154
        $pattern = '/[^' . \preg_quote($alphabet, '/') . ']/';
402✔
155

156
        if (\preg_match($pattern, $number, $matches) === 1) {
402✔
157
            throw NumberFormatException::charNotInAlphabet($matches[0]);
24✔
158
        }
159

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

162
        return new BigInteger($number);
378✔
163
    }
164

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

190
        $twosComplement = false;
1,221✔
191

192
        if ($signed) {
1,221✔
193
            $x = \ord($value[0]);
984✔
194

195
            if (($twosComplement = ($x >= 0x80))) {
984✔
196
                $value = ~$value;
906✔
197
            }
198
        }
199

200
        $number = self::fromBase(\bin2hex($value), 16);
1,221✔
201

202
        if ($twosComplement) {
1,221✔
203
            return $number->plus(1)->negated();
906✔
204
        }
205

206
        return $number;
315✔
207
    }
208

209
    /**
210
     * Generates a pseudo-random number in the range 0 to 2^numBits - 1.
211
     *
212
     * Using the default random bytes generator, this method is suitable for cryptographic use.
213
     *
214
     * @psalm-param (callable(int): string)|null $randomBytesGenerator
215
     *
216
     * @param int           $numBits              The number of bits.
217
     * @param callable|null $randomBytesGenerator A function that accepts a number of bytes as an integer, and returns a
218
     *                                            string of random bytes of the given length. Defaults to the
219
     *                                            `random_bytes()` function.
220
     *
221
     * @throws \InvalidArgumentException If $numBits is negative.
222
     */
223
    public static function randomBits(int $numBits, ?callable $randomBytesGenerator = null) : BigInteger
224
    {
225
        if ($numBits < 0) {
165✔
226
            throw new \InvalidArgumentException('The number of bits cannot be negative.');
3✔
227
        }
228

229
        if ($numBits === 0) {
162✔
230
            return BigInteger::zero();
3✔
231
        }
232

233
        if ($randomBytesGenerator === null) {
159✔
UNCOV
234
            $randomBytesGenerator = random_bytes(...);
×
235
        }
236

237
        /** @var int<1, max> $byteLength */
238
        $byteLength = \intdiv($numBits - 1, 8) + 1;
159✔
239

240
        $extraBits = ($byteLength * 8 - $numBits);
159✔
241
        $bitmask   = \chr(0xFF >> $extraBits);
159✔
242

243
        $randomBytes    = $randomBytesGenerator($byteLength);
159✔
244
        $randomBytes[0] = $randomBytes[0] & $bitmask;
159✔
245

246
        return self::fromBytes($randomBytes, false);
159✔
247
    }
248

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

274
        if ($min->isGreaterThan($max)) {
84✔
275
            throw new MathException('$min cannot be greater than $max.');
3✔
276
        }
277

278
        if ($min->isEqualTo($max)) {
81✔
279
            return $min;
3✔
280
        }
281

282
        $diff      = $max->minus($min);
78✔
283
        $bitLength = $diff->getBitLength();
78✔
284

285
        // try until the number is in range (50% to 100% chance of success)
286
        do {
287
            $randomNumber = self::randomBits($bitLength, $randomBytesGenerator);
78✔
288
        } while ($randomNumber->isGreaterThan($diff));
78✔
289

290
        return $randomNumber->plus($min);
78✔
291
    }
292

293
    /**
294
     * Returns a BigInteger representing zero.
295
     *
296
     * @pure
297
     */
298
    public static function zero() : BigInteger
299
    {
300
        /** @var BigInteger|null $zero */
301
        static $zero;
111✔
302

303
        if ($zero === null) {
111✔
304
            $zero = new BigInteger('0');
×
305
        }
306

307
        return $zero;
111✔
308
    }
309

310
    /**
311
     * Returns a BigInteger representing one.
312
     *
313
     * @pure
314
     */
315
    public static function one() : BigInteger
316
    {
317
        /** @var BigInteger|null $one */
318
        static $one;
444✔
319

320
        if ($one === null) {
444✔
321
            $one = new BigInteger('1');
3✔
322
        }
323

324
        return $one;
444✔
325
    }
326

327
    /**
328
     * Returns a BigInteger representing ten.
329
     *
330
     * @pure
331
     */
332
    public static function ten() : BigInteger
333
    {
334
        /** @var BigInteger|null $ten */
335
        static $ten;
6✔
336

337
        if ($ten === null) {
6✔
338
            $ten = new BigInteger('10');
3✔
339
        }
340

341
        return $ten;
6✔
342
    }
343

344
    /**
345
     * @pure
346
     */
347
    public static function gcdMultiple(BigInteger $a, BigInteger ...$n): BigInteger
348
    {
349
        $result = $a;
1,563✔
350

351
        foreach ($n as $next) {
1,563✔
352
            $result = $result->gcd($next);
1,548✔
353

354
            if ($result->isEqualTo(1)) {
1,548✔
355
                return $result;
345✔
356
            }
357
        }
358

359
        return $result;
1,218✔
360
    }
361

362
    /**
363
     * Returns the sum of this number and the given one.
364
     *
365
     * @param BigNumber|int|float|string $that The number to add. Must be convertible to a BigInteger.
366
     *
367
     * @return static The sum, as a BigInteger.
368
     *
369
     * @throws MathException If the operand is not a valid number or is not convertible to a BigInteger.
370
     */
371
    #[Override]
372
    public function plus(BigNumber|int|float|string $that) : static
373
    {
374
        $that = BigInteger::of($that);
1,569✔
375

376
        if ($that->value === '0') {
1,569✔
377
            return $this;
21✔
378
        }
379

380
        if ($this->value === '0') {
1,548✔
381
            return $that;
63✔
382
        }
383

384
        $value = CalculatorRegistry::get()->add($this->value, $that->value);
1,506✔
385

386
        return new BigInteger($value);
1,506✔
387
    }
388

389
    /**
390
     * Returns the difference of this number and the given one.
391
     *
392
     * @param BigNumber|int|float|string $that The number to subtract. Must be convertible to a BigInteger.
393
     *
394
     * @return static The difference, as a BigInteger.
395
     *
396
     * @throws MathException If the operand is not a valid number or is not convertible to a BigInteger.
397
     */
398
    #[Override]
399
    public function minus(BigNumber|int|float|string $that) : static
400
    {
401
        $that = BigInteger::of($that);
888✔
402

403
        if ($that->value === '0') {
888✔
404
            return $this;
24✔
405
        }
406

407
        $value = CalculatorRegistry::get()->sub($this->value, $that->value);
870✔
408

409
        return new BigInteger($value);
870✔
410
    }
411

412
    /**
413
     * Returns the product of this number and the given one.
414
     *
415
     * @param BigNumber|int|float|string $that The multiplier. Must be convertible to a BigInteger.
416
     *
417
     * @return static The product, as a BigInteger.
418
     *
419
     * @throws MathException If the multiplier is not a valid number or is not convertible to a BigInteger.
420
     */
421
    #[Override]
422
    public function multipliedBy(BigNumber|int|float|string $that) : static
423
    {
424
        $that = BigInteger::of($that);
1,149✔
425

426
        if ($that->value === '1') {
1,149✔
427
            return $this;
270✔
428
        }
429

430
        if ($this->value === '1') {
1,137✔
431
            return $that;
294✔
432
        }
433

434
        $value = CalculatorRegistry::get()->mul($this->value, $that->value);
1,050✔
435

436
        return new BigInteger($value);
1,050✔
437
    }
438

439
    /**
440
     * Returns the result of the division of this number by the given one.
441
     *
442
     * @param BigNumber|int|float|string $that         The divisor. Must be convertible to a BigInteger.
443
     * @param RoundingMode               $roundingMode An optional rounding mode, defaults to `UNNECESSARY`.
444
     *
445
     * @throws MathException If the divisor is not a valid number, is not convertible to a BigInteger, is zero,
446
     *                       or rounding is necessary but `RoundingMode::UNNECESSARY` was provided.
447
     */
448
    #[Override]
449
    public function dividedBy(BigNumber|int|float|string $that, RoundingMode $roundingMode = RoundingMode::UNNECESSARY) : static
450
    {
451
        $that = BigInteger::of($that);
1,980✔
452

453
        if ($that->value === '1') {
1,971✔
454
            return $this;
3✔
455
        }
456

457
        if ($that->value === '0') {
1,968✔
458
            throw DivisionByZeroException::divisionByZero();
6✔
459
        }
460

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

463
        return new BigInteger($result);
1,869✔
464
    }
465

466
    /**
467
     * Returns this number exponentiated to the given value.
468
     *
469
     * @pure
470
     *
471
     * @throws \InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
472
     */
473
    public function power(int $exponent) : BigInteger
474
    {
475
        if ($exponent === 0) {
1,827✔
476
            return BigInteger::one();
21✔
477
        }
478

479
        if ($exponent === 1) {
1,806✔
480
            return $this;
198✔
481
        }
482

483
        if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
1,608✔
484
            throw new \InvalidArgumentException(\sprintf(
6✔
485
                'The exponent %d is not in the range 0 to %d.',
6✔
486
                $exponent,
6✔
487
                Calculator::MAX_POWER
6✔
488
            ));
6✔
489
        }
490

491
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,602✔
492
    }
493

494
    /**
495
     * Returns the quotient of the division of this number by the given one.
496
     *
497
     * @pure
498
     *
499
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
500
     *
501
     * @throws DivisionByZeroException If the divisor is zero.
502
     */
503
    public function quotient(BigNumber|int|float|string $that) : BigInteger
504
    {
505
        $that = BigInteger::of($that);
972✔
506

507
        if ($that->value === '1') {
972✔
508
            return $this;
69✔
509
        }
510

511
        if ($that->value === '0') {
903✔
512
            throw DivisionByZeroException::divisionByZero();
3✔
513
        }
514

515
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
900✔
516

517
        return new BigInteger($quotient);
900✔
518
    }
519

520
    /**
521
     * Returns the remainder of the division of this number by the given one.
522
     *
523
     * The remainder, when non-zero, has the same sign as the dividend.
524
     *
525
     * @pure
526
     *
527
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
528
     *
529
     * @throws DivisionByZeroException If the divisor is zero.
530
     */
531
    public function remainder(BigNumber|int|float|string $that) : BigInteger
532
    {
533
        $that = BigInteger::of($that);
159✔
534

535
        if ($that->value === '1') {
159✔
536
            return BigInteger::zero();
12✔
537
        }
538

539
        if ($that->value === '0') {
147✔
540
            throw DivisionByZeroException::divisionByZero();
3✔
541
        }
542

543
        $remainder = CalculatorRegistry::get()->divR($this->value, $that->value);
144✔
544

545
        return new BigInteger($remainder);
144✔
546
    }
547

548
    /**
549
     * Returns the quotient and remainder of the division of this number by the given one.
550
     *
551
     * @pure
552
     *
553
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
554
     *
555
     * @return BigInteger[] An array containing the quotient and the remainder.
556
     *
557
     * @psalm-return array{BigInteger, BigInteger}
558
     *
559
     * @throws DivisionByZeroException If the divisor is zero.
560
     */
561
    public function quotientAndRemainder(BigNumber|int|float|string $that) : array
562
    {
563
        $that = BigInteger::of($that);
159✔
564

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

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

571
        return [
156✔
572
            new BigInteger($quotient),
156✔
573
            new BigInteger($remainder)
156✔
574
        ];
156✔
575
    }
576

577
    /**
578
     * Returns the modulo of this number and the given one.
579
     *
580
     * The modulo operation yields the same result as the remainder operation when both operands are of the same sign,
581
     * and may differ when signs are different.
582
     *
583
     * The result of the modulo operation, when non-zero, has the same sign as the divisor.
584
     *
585
     * @pure
586
     *
587
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
588
     *
589
     * @throws DivisionByZeroException If the divisor is zero.
590
     */
591
    public function mod(BigNumber|int|float|string $that) : BigInteger
592
    {
593
        $that = BigInteger::of($that);
195✔
594

595
        if ($that->value === '0') {
195✔
596
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
597
        }
598

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

601
        return new BigInteger($value);
192✔
602
    }
603

604
    /**
605
     * Returns the modular multiplicative inverse of this BigInteger modulo $m.
606
     *
607
     * @pure
608
     *
609
     * @throws DivisionByZeroException If $m is zero.
610
     * @throws NegativeNumberException If $m is negative.
611
     * @throws MathException           If this BigInteger has no multiplicative inverse mod m (that is, this BigInteger
612
     *                                 is not relatively prime to m).
613
     */
614
    public function modInverse(BigInteger $m) : BigInteger
615
    {
616
        if ($m->value === '0') {
66✔
617
            throw DivisionByZeroException::modulusMustNotBeZero();
6✔
618
        }
619

620
        if ($m->isNegative()) {
60✔
621
            throw new NegativeNumberException('Modulus must not be negative.');
3✔
622
        }
623

624
        if ($m->value === '1') {
57✔
625
            return BigInteger::zero();
3✔
626
        }
627

628
        $value = CalculatorRegistry::get()->modInverse($this->value, $m->value);
54✔
629

630
        if ($value === null) {
54✔
631
            throw new MathException('Unable to compute the modInverse for the given modulus.');
15✔
632
        }
633

634
        return new BigInteger($value);
39✔
635
    }
636

637
    /**
638
     * Returns this number raised into power with modulo.
639
     *
640
     * This operation only works on positive numbers.
641
     *
642
     * @pure
643
     *
644
     * @param BigNumber|int|float|string $exp The exponent. Must be positive or zero.
645
     * @param BigNumber|int|float|string $mod The modulus. Must be strictly positive.
646
     *
647
     * @throws NegativeNumberException If any of the operands is negative.
648
     * @throws DivisionByZeroException If the modulus is zero.
649
     */
650
    public function modPow(BigNumber|int|float|string $exp, BigNumber|int|float|string $mod) : BigInteger
651
    {
652
        $exp = BigInteger::of($exp);
47✔
653
        $mod = BigInteger::of($mod);
47✔
654

655
        if ($this->isNegative() || $exp->isNegative() || $mod->isNegative()) {
47✔
656
            throw new NegativeNumberException('The operands cannot be negative.');
9✔
657
        }
658

659
        if ($mod->isZero()) {
38✔
660
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
661
        }
662

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

665
        return new BigInteger($result);
35✔
666
    }
667

668
    /**
669
     * Returns the greatest common divisor of this number and the given one.
670
     *
671
     * The GCD is always positive, unless both operands are zero, in which case it is zero.
672
     *
673
     * @pure
674
     *
675
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
676
     */
677
    public function gcd(BigNumber|int|float|string $that) : BigInteger
678
    {
679
        $that = BigInteger::of($that);
3,201✔
680

681
        if ($that->value === '0' && $this->value[0] !== '-') {
3,201✔
682
            return $this;
60✔
683
        }
684

685
        if ($this->value === '0' && $that->value[0] !== '-') {
3,141✔
686
            return $that;
30✔
687
        }
688

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

691
        return new BigInteger($value);
3,111✔
692
    }
693

694
    /**
695
     * Returns the integer square root number of this number, rounded down.
696
     *
697
     * The result is the largest x such that x² ≤ n.
698
     *
699
     * @pure
700
     *
701
     * @throws NegativeNumberException If this number is negative.
702
     */
703
    public function sqrt() : BigInteger
704
    {
705
        if ($this->value[0] === '-') {
1,008✔
706
            throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
3✔
707
        }
708

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

711
        return new BigInteger($value);
1,005✔
712
    }
713

714
    /**
715
     * Returns the absolute value of this number.
716
     *
717
     * @pure
718
     */
719
    public function abs() : BigInteger
720
    {
721
        return $this->isNegative() ? $this->negated() : $this;
678✔
722
    }
723

724
    /**
725
     * Returns the inverse of this number.
726
     *
727
     * @pure
728
     */
729
    public function negated() : BigInteger
730
    {
731
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
2,838✔
732
    }
733

734
    /**
735
     * Returns the integer bitwise-and combined with another integer.
736
     *
737
     * This method returns a negative BigInteger if and only if both operands are negative.
738
     *
739
     * @pure
740
     *
741
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
742
     */
743
    public function and(BigNumber|int|float|string $that) : BigInteger
744
    {
745
        $that = BigInteger::of($that);
153✔
746

747
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
748
    }
749

750
    /**
751
     * Returns the integer bitwise-or combined with another integer.
752
     *
753
     * This method returns a negative BigInteger if and only if either of the operands is negative.
754
     *
755
     * @pure
756
     *
757
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
758
     */
759
    public function or(BigNumber|int|float|string $that) : BigInteger
760
    {
761
        $that = BigInteger::of($that);
138✔
762

763
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
764
    }
765

766
    /**
767
     * Returns the integer bitwise-xor combined with another integer.
768
     *
769
     * This method returns a negative BigInteger if and only if exactly one of the operands is negative.
770
     *
771
     * @pure
772
     *
773
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
774
     */
775
    public function xor(BigNumber|int|float|string $that) : BigInteger
776
    {
777
        $that = BigInteger::of($that);
144✔
778

779
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
780
    }
781

782
    /**
783
     * Returns the bitwise-not of this BigInteger.
784
     *
785
     * @pure
786
     */
787
    public function not() : BigInteger
788
    {
789
        return $this->negated()->minus(1);
57✔
790
    }
791

792
    /**
793
     * Returns the integer left shifted by a given number of bits.
794
     *
795
     * @pure
796
     */
797
    public function shiftedLeft(int $distance) : BigInteger
798
    {
799
        if ($distance === 0) {
594✔
800
            return $this;
6✔
801
        }
802

803
        if ($distance < 0) {
588✔
804
            return $this->shiftedRight(- $distance);
198✔
805
        }
806

807
        return $this->multipliedBy(BigInteger::of(2)->power($distance));
390✔
808
    }
809

810
    /**
811
     * Returns the integer right shifted by a given number of bits.
812
     *
813
     * @pure
814
     */
815
    public function shiftedRight(int $distance) : BigInteger
816
    {
817
        if ($distance === 0) {
1,518✔
818
            return $this;
66✔
819
        }
820

821
        if ($distance < 0) {
1,452✔
822
            return $this->shiftedLeft(- $distance);
195✔
823
        }
824

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

827
        if ($this->isPositiveOrZero()) {
1,257✔
828
            return $this->quotient($operand);
672✔
829
        }
830

831
        return $this->dividedBy($operand, RoundingMode::UP);
585✔
832
    }
833

834
    /**
835
     * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
836
     *
837
     * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation.
838
     * Computes (ceil(log2(this < 0 ? -this : this+1))).
839
     *
840
     * @pure
841
     */
842
    public function getBitLength() : int
843
    {
844
        if ($this->value === '0') {
321✔
845
            return 0;
12✔
846
        }
847

848
        if ($this->isNegative()) {
315✔
849
            return $this->abs()->minus(1)->getBitLength();
120✔
850
        }
851

852
        return \strlen($this->toBase(2));
309✔
853
    }
854

855
    /**
856
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
857
     *
858
     * Returns -1 if this BigInteger contains no one bits.
859
     *
860
     * @pure
861
     */
862
    public function getLowestSetBit() : int
863
    {
864
        $n = $this;
81✔
865
        $bitLength = $this->getBitLength();
81✔
866

867
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
868
            if ($n->isOdd()) {
81✔
869
                return $i;
78✔
870
            }
871

872
            $n = $n->shiftedRight(1);
51✔
873
        }
874

875
        return -1;
3✔
876
    }
877

878
    /**
879
     * Returns whether this number is even.
880
     *
881
     * @pure
882
     */
883
    public function isEven() : bool
884
    {
885
        return \in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
886
    }
887

888
    /**
889
     * Returns whether this number is odd.
890
     *
891
     * @pure
892
     */
893
    public function isOdd() : bool
894
    {
895
        return \in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
896
    }
897

898
    /**
899
     * Returns true if and only if the designated bit is set.
900
     *
901
     * Computes ((this & (1<<n)) != 0).
902
     *
903
     * @pure
904
     *
905
     * @param int $n The bit to test, 0-based.
906
     *
907
     * @throws \InvalidArgumentException If the bit to test is negative.
908
     */
909
    public function testBit(int $n) : bool
910
    {
911
        if ($n < 0) {
873✔
912
            throw new \InvalidArgumentException('The bit to test cannot be negative.');
3✔
913
        }
914

915
        return $this->shiftedRight($n)->isOdd();
870✔
916
    }
917

918
    #[Override]
919
    public function compareTo(BigNumber|int|float|string $that) : int
920
    {
921
        $that = BigNumber::of($that);
2,285✔
922

923
        if ($that instanceof BigInteger) {
2,285✔
924
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,177✔
925
        }
926

927
        return - $that->compareTo($this);
108✔
928
    }
929

930
    #[Override]
931
    public function getSign() : int
932
    {
933
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
3,173✔
934
    }
935

936
    #[Override]
937
    public function toBigInteger() : BigInteger
938
    {
939
        return $this;
13,088✔
940
    }
941

942
    #[Override]
943
    public function toBigDecimal() : BigDecimal
944
    {
945
        return self::newBigDecimal($this->value);
3,897✔
946
    }
947

948
    #[Override]
949
    public function toBigRational() : BigRational
950
    {
951
        return self::newBigRational($this, BigInteger::one(), false);
393✔
952
    }
953

954
    #[Override]
955
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal
956
    {
957
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
958
    }
959

960
    #[Override]
961
    public function toInt() : int
962
    {
963
        $intValue = (int) $this->value;
87✔
964

965
        if ($this->value !== (string) $intValue) {
87✔
966
            throw IntegerOverflowException::toIntOverflow($this);
15✔
967
        }
968

969
        return $intValue;
72✔
970
    }
971

972
    #[Override]
973
    public function toFloat() : float
974
    {
975
        return (float) $this->value;
48✔
976
    }
977

978
    /**
979
     * Returns a string representation of this number in the given base.
980
     *
981
     * The output will always be lowercase for bases greater than 10.
982
     *
983
     * @pure
984
     *
985
     * @throws \InvalidArgumentException If the base is out of range.
986
     */
987
    public function toBase(int $base) : string
988
    {
989
        if ($base === 10) {
1,293✔
990
            return $this->value;
12✔
991
        }
992

993
        if ($base < 2 || $base > 36) {
1,281✔
994
            throw new \InvalidArgumentException(\sprintf('Base %d is out of range [2, 36]', $base));
15✔
995
        }
996

997
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,266✔
998
    }
999

1000
    /**
1001
     * Returns a string representation of this number in an arbitrary base with a custom alphabet.
1002
     *
1003
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers;
1004
     * a NegativeNumberException will be thrown when attempting to call this method on a negative number.
1005
     *
1006
     * @pure
1007
     *
1008
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
1009
     *
1010
     * @throws NegativeNumberException   If this number is negative.
1011
     * @throws \InvalidArgumentException If the given alphabet does not contain at least 2 chars.
1012
     */
1013
    public function toArbitraryBase(string $alphabet) : string
1014
    {
1015
        $base = \strlen($alphabet);
135✔
1016

1017
        if ($base < 2) {
135✔
1018
            throw new \InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
1019
        }
1020

1021
        if ($this->value[0] === '-') {
129✔
1022
            throw new NegativeNumberException(__FUNCTION__ . '() does not support negative numbers.');
3✔
1023
        }
1024

1025
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1026
    }
1027

1028
    /**
1029
     * Returns a string of bytes containing the binary representation of this BigInteger.
1030
     *
1031
     * The string is in big-endian byte-order: the most significant byte is in the zeroth element.
1032
     *
1033
     * If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to
1034
     * the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the
1035
     * number is negative.
1036
     *
1037
     * The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit
1038
     * if `$signed` is true.
1039
     *
1040
     * This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match.
1041
     *
1042
     * @pure
1043
     *
1044
     * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit.
1045
     *
1046
     * @throws NegativeNumberException If $signed is false, and the number is negative.
1047
     */
1048
    public function toBytes(bool $signed = true) : string
1049
    {
1050
        if (! $signed && $this->isNegative()) {
534✔
1051
            throw new NegativeNumberException('Cannot convert a negative number to a byte string when $signed is false.');
3✔
1052
        }
1053

1054
        $hex = $this->abs()->toBase(16);
531✔
1055

1056
        if (\strlen($hex) % 2 !== 0) {
531✔
1057
            $hex = '0' . $hex;
219✔
1058
        }
1059

1060
        $baseHexLength = \strlen($hex);
531✔
1061

1062
        if ($signed) {
531✔
1063
            if ($this->isNegative()) {
492✔
1064
                $bin = \hex2bin($hex);
453✔
1065
                assert($bin !== false);
1066

1067
                $hex = \bin2hex(~$bin);
453✔
1068
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1069

1070
                $hexLength = \strlen($hex);
453✔
1071

1072
                if ($hexLength < $baseHexLength) {
453✔
1073
                    $hex = \str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1074
                }
1075

1076
                if ($hex[0] < '8') {
453✔
1077
                    $hex = 'FF' . $hex;
114✔
1078
                }
1079
            } else {
1080
                if ($hex[0] >= '8') {
39✔
1081
                    $hex = '00' . $hex;
21✔
1082
                }
1083
            }
1084
        }
1085

1086
        $result = \hex2bin($hex);
531✔
1087
        assert($result !== false);
1088

1089
        return $result;
531✔
1090
    }
1091

1092
    /**
1093
     * @return numeric-string
1094
     */
1095
    #[Override]
1096
    public function __toString() : string
1097
    {
1098
        /** @var numeric-string */
1099
        return $this->value;
12,921✔
1100
    }
1101

1102
    /**
1103
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1104
     *
1105
     * @internal
1106
     *
1107
     * @return array{value: string}
1108
     */
1109
    public function __serialize(): array
1110
    {
1111
        return ['value' => $this->value];
6✔
1112
    }
1113

1114
    /**
1115
     * This method is only here to allow unserializing the object and cannot be accessed directly.
1116
     *
1117
     * @internal
1118
     *
1119
     * @param array{value: string} $data
1120
     *
1121
     * @throws \LogicException
1122
     */
1123
    public function __unserialize(array $data): void
1124
    {
1125
        /** @phpstan-ignore isset.initializedProperty */
1126
        if (isset($this->value)) {
9✔
1127
            throw new \LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
1128
        }
1129

1130
        /** @phpstan-ignore deadCode.unreachable */
1131
        $this->value = $data['value'];
6✔
1132
    }
1133
}
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