Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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
 
14
/**
15
 * An arbitrary-size integer.
16
 *
17
 * All methods accepting a number as a parameter accept either a BigInteger instance,
18
 * an integer, or a string representing an arbitrary size integer.
19
 *
20
 * @psalm-immutable
21
 */
22
final class BigInteger extends BigNumber
23
{
24
    /**
25
     * The value, as a string of digits with optional leading minus sign.
26
     *
27
     * No leading zeros must be present.
28
     * No leading minus sign must be present if the number is zero.
29
     */
30
    private string $value;
31
 
32
    /**
33
     * Protected constructor. Use a factory method to obtain an instance.
34
     *
35
     * @param string $value A string of digits, with optional leading minus sign.
36
     */
37
    protected function __construct(string $value)
38
    {
39
        $this->value = $value;
40
    }
41
 
42
    /**
43
     * Creates a BigInteger of the given value.
44
     *
45
     * @throws MathException If the value cannot be converted to a BigInteger.
46
     *
47
     * @psalm-pure
48
     */
399 lars 49
    public static function of(BigNumber|int|float|string $value) : BigInteger
148 lars 50
    {
51
        return parent::of($value)->toBigInteger();
52
    }
53
 
54
    /**
55
     * Creates a number from a string in a given base.
56
     *
57
     * The string can optionally be prefixed with the `+` or `-` sign.
58
     *
59
     * Bases greater than 36 are not supported by this method, as there is no clear consensus on which of the lowercase
60
     * or uppercase characters should come first. Instead, this method accepts any base up to 36, and does not
61
     * differentiate lowercase and uppercase characters, which are considered equal.
62
     *
63
     * For bases greater than 36, and/or custom alphabets, use the fromArbitraryBase() method.
64
     *
65
     * @param string $number The number to convert, in the given base.
66
     * @param int    $base   The base of the number, between 2 and 36.
67
     *
68
     * @throws NumberFormatException     If the number is empty, or contains invalid chars for the given base.
69
     * @throws \InvalidArgumentException If the base is out of range.
70
     *
71
     * @psalm-pure
72
     */
73
    public static function fromBase(string $number, int $base) : BigInteger
74
    {
75
        if ($number === '') {
76
            throw new NumberFormatException('The number cannot be empty.');
77
        }
78
 
79
        if ($base < 2 || $base > 36) {
80
            throw new \InvalidArgumentException(\sprintf('Base %d is not in range 2 to 36.', $base));
81
        }
82
 
83
        if ($number[0] === '-') {
84
            $sign = '-';
85
            $number = \substr($number, 1);
86
        } elseif ($number[0] === '+') {
87
            $sign = '';
88
            $number = \substr($number, 1);
89
        } else {
90
            $sign = '';
91
        }
92
 
93
        if ($number === '') {
94
            throw new NumberFormatException('The number cannot be empty.');
95
        }
96
 
97
        $number = \ltrim($number, '0');
98
 
99
        if ($number === '') {
100
            // The result will be the same in any base, avoid further calculation.
101
            return BigInteger::zero();
102
        }
103
 
104
        if ($number === '1') {
105
            // The result will be the same in any base, avoid further calculation.
106
            return new BigInteger($sign . '1');
107
        }
108
 
109
        $pattern = '/[^' . \substr(Calculator::ALPHABET, 0, $base) . ']/';
110
 
111
        if (\preg_match($pattern, \strtolower($number), $matches) === 1) {
112
            throw new NumberFormatException(\sprintf('"%s" is not a valid character in base %d.', $matches[0], $base));
113
        }
114
 
115
        if ($base === 10) {
116
            // The number is usable as is, avoid further calculation.
117
            return new BigInteger($sign . $number);
118
        }
119
 
120
        $result = Calculator::get()->fromBase($number, $base);
121
 
122
        return new BigInteger($sign . $result);
123
    }
124
 
125
    /**
126
     * Parses a string containing an integer in an arbitrary base, using a custom alphabet.
127
     *
128
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers.
129
     *
130
     * @param string $number   The number to parse.
131
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
132
     *
133
     * @throws NumberFormatException     If the given number is empty or contains invalid chars for the given alphabet.
134
     * @throws \InvalidArgumentException If the alphabet does not contain at least 2 chars.
135
     *
136
     * @psalm-pure
137
     */
138
    public static function fromArbitraryBase(string $number, string $alphabet) : BigInteger
139
    {
140
        if ($number === '') {
141
            throw new NumberFormatException('The number cannot be empty.');
142
        }
143
 
144
        $base = \strlen($alphabet);
145
 
146
        if ($base < 2) {
147
            throw new \InvalidArgumentException('The alphabet must contain at least 2 chars.');
148
        }
149
 
150
        $pattern = '/[^' . \preg_quote($alphabet, '/') . ']/';
151
 
152
        if (\preg_match($pattern, $number, $matches) === 1) {
153
            throw NumberFormatException::charNotInAlphabet($matches[0]);
154
        }
155
 
156
        $number = Calculator::get()->fromArbitraryBase($number, $alphabet, $base);
157
 
158
        return new BigInteger($number);
159
    }
160
 
161
    /**
162
     * Translates a string of bytes containing the binary representation of a BigInteger into a BigInteger.
163
     *
164
     * The input string is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element.
165
     *
166
     * If `$signed` is true, the input is assumed to be in two's-complement representation, and the leading bit is
167
     * interpreted as a sign bit. If `$signed` is false, the input is interpreted as an unsigned number, and the
168
     * resulting BigInteger will always be positive or zero.
169
     *
170
     * This method can be used to retrieve a number exported by `toBytes()`, as long as the `$signed` flags match.
171
     *
172
     * @param string $value  The byte string.
173
     * @param bool   $signed Whether to interpret as a signed number in two's-complement representation with a leading
174
     *                       sign bit.
175
     *
176
     * @throws NumberFormatException If the string is empty.
177
     */
178
    public static function fromBytes(string $value, bool $signed = true) : BigInteger
179
    {
180
        if ($value === '') {
181
            throw new NumberFormatException('The byte string must not be empty.');
182
        }
183
 
184
        $twosComplement = false;
185
 
186
        if ($signed) {
187
            $x = \ord($value[0]);
188
 
189
            if (($twosComplement = ($x >= 0x80))) {
190
                $value = ~$value;
191
            }
192
        }
193
 
194
        $number = self::fromBase(\bin2hex($value), 16);
195
 
196
        if ($twosComplement) {
197
            return $number->plus(1)->negated();
198
        }
199
 
200
        return $number;
201
    }
202
 
203
    /**
204
     * Generates a pseudo-random number in the range 0 to 2^numBits - 1.
205
     *
206
     * Using the default random bytes generator, this method is suitable for cryptographic use.
207
     *
399 lars 208
     * @psalm-param (callable(int): string)|null $randomBytesGenerator
148 lars 209
     *
210
     * @param int           $numBits              The number of bits.
211
     * @param callable|null $randomBytesGenerator A function that accepts a number of bytes as an integer, and returns a
212
     *                                            string of random bytes of the given length. Defaults to the
213
     *                                            `random_bytes()` function.
214
     *
215
     * @throws \InvalidArgumentException If $numBits is negative.
216
     */
217
    public static function randomBits(int $numBits, ?callable $randomBytesGenerator = null) : BigInteger
218
    {
219
        if ($numBits < 0) {
220
            throw new \InvalidArgumentException('The number of bits cannot be negative.');
221
        }
222
 
223
        if ($numBits === 0) {
224
            return BigInteger::zero();
225
        }
226
 
227
        if ($randomBytesGenerator === null) {
228
            $randomBytesGenerator = 'random_bytes';
229
        }
230
 
231
        $byteLength = \intdiv($numBits - 1, 8) + 1;
232
 
233
        $extraBits = ($byteLength * 8 - $numBits);
234
        $bitmask   = \chr(0xFF >> $extraBits);
235
 
236
        $randomBytes    = $randomBytesGenerator($byteLength);
237
        $randomBytes[0] = $randomBytes[0] & $bitmask;
238
 
239
        return self::fromBytes($randomBytes, false);
240
    }
241
 
242
    /**
243
     * Generates a pseudo-random number between `$min` and `$max`.
244
     *
245
     * Using the default random bytes generator, this method is suitable for cryptographic use.
246
     *
247
     * @psalm-param (callable(int): string)|null $randomBytesGenerator
248
     *
249
     * @param BigNumber|int|float|string $min                  The lower bound. Must be convertible to a BigInteger.
250
     * @param BigNumber|int|float|string $max                  The upper bound. Must be convertible to a BigInteger.
251
     * @param callable|null              $randomBytesGenerator A function that accepts a number of bytes as an integer,
252
     *                                                         and returns a string of random bytes of the given length.
253
     *                                                         Defaults to the `random_bytes()` function.
254
     *
255
     * @throws MathException If one of the parameters cannot be converted to a BigInteger,
256
     *                       or `$min` is greater than `$max`.
257
     */
399 lars 258
    public static function randomRange(
259
        BigNumber|int|float|string $min,
260
        BigNumber|int|float|string $max,
261
        ?callable $randomBytesGenerator = null
262
    ) : BigInteger {
148 lars 263
        $min = BigInteger::of($min);
264
        $max = BigInteger::of($max);
265
 
266
        if ($min->isGreaterThan($max)) {
267
            throw new MathException('$min cannot be greater than $max.');
268
        }
269
 
270
        if ($min->isEqualTo($max)) {
271
            return $min;
272
        }
273
 
274
        $diff      = $max->minus($min);
275
        $bitLength = $diff->getBitLength();
276
 
277
        // try until the number is in range (50% to 100% chance of success)
278
        do {
279
            $randomNumber = self::randomBits($bitLength, $randomBytesGenerator);
280
        } while ($randomNumber->isGreaterThan($diff));
281
 
282
        return $randomNumber->plus($min);
283
    }
284
 
285
    /**
286
     * Returns a BigInteger representing zero.
287
     *
288
     * @psalm-pure
289
     */
290
    public static function zero() : BigInteger
291
    {
292
        /**
293
         * @psalm-suppress ImpureStaticVariable
294
         * @var BigInteger|null $zero
295
         */
296
        static $zero;
297
 
298
        if ($zero === null) {
299
            $zero = new BigInteger('0');
300
        }
301
 
302
        return $zero;
303
    }
304
 
305
    /**
306
     * Returns a BigInteger representing one.
307
     *
308
     * @psalm-pure
309
     */
310
    public static function one() : BigInteger
311
    {
312
        /**
313
         * @psalm-suppress ImpureStaticVariable
314
         * @var BigInteger|null $one
315
         */
316
        static $one;
317
 
318
        if ($one === null) {
319
            $one = new BigInteger('1');
320
        }
321
 
322
        return $one;
323
    }
324
 
325
    /**
326
     * Returns a BigInteger representing ten.
327
     *
328
     * @psalm-pure
329
     */
330
    public static function ten() : BigInteger
331
    {
332
        /**
333
         * @psalm-suppress ImpureStaticVariable
334
         * @var BigInteger|null $ten
335
         */
336
        static $ten;
337
 
338
        if ($ten === null) {
339
            $ten = new BigInteger('10');
340
        }
341
 
342
        return $ten;
343
    }
344
 
345
    public static function gcdMultiple(BigInteger $a, BigInteger ...$n): BigInteger
346
    {
347
        $result = $a;
348
 
349
        foreach ($n as $next) {
350
            $result = $result->gcd($next);
351
 
352
            if ($result->isEqualTo(1)) {
353
                return $result;
354
            }
355
        }
356
 
357
        return $result;
358
    }
359
 
360
    /**
361
     * Returns the sum of this number and the given one.
362
     *
363
     * @param BigNumber|int|float|string $that The number to add. Must be convertible to a BigInteger.
364
     *
365
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
366
     */
399 lars 367
    public function plus(BigNumber|int|float|string $that) : BigInteger
148 lars 368
    {
369
        $that = BigInteger::of($that);
370
 
371
        if ($that->value === '0') {
372
            return $this;
373
        }
374
 
375
        if ($this->value === '0') {
376
            return $that;
377
        }
378
 
379
        $value = Calculator::get()->add($this->value, $that->value);
380
 
381
        return new BigInteger($value);
382
    }
383
 
384
    /**
385
     * Returns the difference of this number and the given one.
386
     *
387
     * @param BigNumber|int|float|string $that The number to subtract. Must be convertible to a BigInteger.
388
     *
389
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
390
     */
399 lars 391
    public function minus(BigNumber|int|float|string $that) : BigInteger
148 lars 392
    {
393
        $that = BigInteger::of($that);
394
 
395
        if ($that->value === '0') {
396
            return $this;
397
        }
398
 
399
        $value = Calculator::get()->sub($this->value, $that->value);
400
 
401
        return new BigInteger($value);
402
    }
403
 
404
    /**
405
     * Returns the product of this number and the given one.
406
     *
407
     * @param BigNumber|int|float|string $that The multiplier. Must be convertible to a BigInteger.
408
     *
409
     * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigInteger.
410
     */
399 lars 411
    public function multipliedBy(BigNumber|int|float|string $that) : BigInteger
148 lars 412
    {
413
        $that = BigInteger::of($that);
414
 
415
        if ($that->value === '1') {
416
            return $this;
417
        }
418
 
419
        if ($this->value === '1') {
420
            return $that;
421
        }
422
 
423
        $value = Calculator::get()->mul($this->value, $that->value);
424
 
425
        return new BigInteger($value);
426
    }
427
 
428
    /**
429
     * Returns the result of the division of this number by the given one.
430
     *
431
     * @param BigNumber|int|float|string $that         The divisor. Must be convertible to a BigInteger.
432
     * @param int                        $roundingMode An optional rounding mode.
433
     *
434
     * @throws MathException If the divisor is not a valid number, is not convertible to a BigInteger, is zero,
435
     *                       or RoundingMode::UNNECESSARY is used and the remainder is not zero.
436
     */
399 lars 437
    public function dividedBy(BigNumber|int|float|string $that, int $roundingMode = RoundingMode::UNNECESSARY) : BigInteger
148 lars 438
    {
439
        $that = BigInteger::of($that);
440
 
441
        if ($that->value === '1') {
442
            return $this;
443
        }
444
 
445
        if ($that->value === '0') {
446
            throw DivisionByZeroException::divisionByZero();
447
        }
448
 
449
        $result = Calculator::get()->divRound($this->value, $that->value, $roundingMode);
450
 
451
        return new BigInteger($result);
452
    }
453
 
454
    /**
455
     * Returns this number exponentiated to the given value.
456
     *
457
     * @throws \InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
458
     */
459
    public function power(int $exponent) : BigInteger
460
    {
461
        if ($exponent === 0) {
462
            return BigInteger::one();
463
        }
464
 
465
        if ($exponent === 1) {
466
            return $this;
467
        }
468
 
469
        if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
470
            throw new \InvalidArgumentException(\sprintf(
471
                'The exponent %d is not in the range 0 to %d.',
472
                $exponent,
473
                Calculator::MAX_POWER
474
            ));
475
        }
476
 
477
        return new BigInteger(Calculator::get()->pow($this->value, $exponent));
478
    }
479
 
480
    /**
481
     * Returns the quotient of the division of this number by the given one.
482
     *
483
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
484
     *
485
     * @throws DivisionByZeroException If the divisor is zero.
486
     */
399 lars 487
    public function quotient(BigNumber|int|float|string $that) : BigInteger
148 lars 488
    {
489
        $that = BigInteger::of($that);
490
 
491
        if ($that->value === '1') {
492
            return $this;
493
        }
494
 
495
        if ($that->value === '0') {
496
            throw DivisionByZeroException::divisionByZero();
497
        }
498
 
499
        $quotient = Calculator::get()->divQ($this->value, $that->value);
500
 
501
        return new BigInteger($quotient);
502
    }
503
 
504
    /**
505
     * Returns the remainder of the division of this number by the given one.
506
     *
507
     * The remainder, when non-zero, has the same sign as the dividend.
508
     *
509
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
510
     *
511
     * @throws DivisionByZeroException If the divisor is zero.
512
     */
399 lars 513
    public function remainder(BigNumber|int|float|string $that) : BigInteger
148 lars 514
    {
515
        $that = BigInteger::of($that);
516
 
517
        if ($that->value === '1') {
518
            return BigInteger::zero();
519
        }
520
 
521
        if ($that->value === '0') {
522
            throw DivisionByZeroException::divisionByZero();
523
        }
524
 
525
        $remainder = Calculator::get()->divR($this->value, $that->value);
526
 
527
        return new BigInteger($remainder);
528
    }
529
 
530
    /**
531
     * Returns the quotient and remainder of the division of this number by the given one.
532
     *
533
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
534
     *
535
     * @return BigInteger[] An array containing the quotient and the remainder.
536
     *
537
     * @throws DivisionByZeroException If the divisor is zero.
538
     */
399 lars 539
    public function quotientAndRemainder(BigNumber|int|float|string $that) : array
148 lars 540
    {
541
        $that = BigInteger::of($that);
542
 
543
        if ($that->value === '0') {
544
            throw DivisionByZeroException::divisionByZero();
545
        }
546
 
547
        [$quotient, $remainder] = Calculator::get()->divQR($this->value, $that->value);
548
 
549
        return [
550
            new BigInteger($quotient),
551
            new BigInteger($remainder)
552
        ];
553
    }
554
 
555
    /**
556
     * Returns the modulo of this number and the given one.
557
     *
558
     * The modulo operation yields the same result as the remainder operation when both operands are of the same sign,
559
     * and may differ when signs are different.
560
     *
561
     * The result of the modulo operation, when non-zero, has the same sign as the divisor.
562
     *
563
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
564
     *
565
     * @throws DivisionByZeroException If the divisor is zero.
566
     */
399 lars 567
    public function mod(BigNumber|int|float|string $that) : BigInteger
148 lars 568
    {
569
        $that = BigInteger::of($that);
570
 
571
        if ($that->value === '0') {
572
            throw DivisionByZeroException::modulusMustNotBeZero();
573
        }
574
 
575
        $value = Calculator::get()->mod($this->value, $that->value);
576
 
577
        return new BigInteger($value);
578
    }
579
 
580
    /**
581
     * Returns the modular multiplicative inverse of this BigInteger modulo $m.
582
     *
583
     * @throws DivisionByZeroException If $m is zero.
584
     * @throws NegativeNumberException If $m is negative.
585
     * @throws MathException           If this BigInteger has no multiplicative inverse mod m (that is, this BigInteger
586
     *                                 is not relatively prime to m).
587
     */
588
    public function modInverse(BigInteger $m) : BigInteger
589
    {
590
        if ($m->value === '0') {
591
            throw DivisionByZeroException::modulusMustNotBeZero();
592
        }
593
 
594
        if ($m->isNegative()) {
595
            throw new NegativeNumberException('Modulus must not be negative.');
596
        }
597
 
598
        if ($m->value === '1') {
599
            return BigInteger::zero();
600
        }
601
 
602
        $value = Calculator::get()->modInverse($this->value, $m->value);
603
 
604
        if ($value === null) {
605
            throw new MathException('Unable to compute the modInverse for the given modulus.');
606
        }
607
 
608
        return new BigInteger($value);
609
    }
610
 
611
    /**
612
     * Returns this number raised into power with modulo.
613
     *
614
     * This operation only works on positive numbers.
615
     *
616
     * @param BigNumber|int|float|string $exp The exponent. Must be positive or zero.
617
     * @param BigNumber|int|float|string $mod The modulus. Must be strictly positive.
618
     *
619
     * @throws NegativeNumberException If any of the operands is negative.
620
     * @throws DivisionByZeroException If the modulus is zero.
621
     */
399 lars 622
    public function modPow(BigNumber|int|float|string $exp, BigNumber|int|float|string $mod) : BigInteger
148 lars 623
    {
624
        $exp = BigInteger::of($exp);
625
        $mod = BigInteger::of($mod);
626
 
627
        if ($this->isNegative() || $exp->isNegative() || $mod->isNegative()) {
628
            throw new NegativeNumberException('The operands cannot be negative.');
629
        }
630
 
631
        if ($mod->isZero()) {
632
            throw DivisionByZeroException::modulusMustNotBeZero();
633
        }
634
 
635
        $result = Calculator::get()->modPow($this->value, $exp->value, $mod->value);
636
 
637
        return new BigInteger($result);
638
    }
639
 
640
    /**
641
     * Returns the greatest common divisor of this number and the given one.
642
     *
643
     * The GCD is always positive, unless both operands are zero, in which case it is zero.
644
     *
645
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
646
     */
399 lars 647
    public function gcd(BigNumber|int|float|string $that) : BigInteger
148 lars 648
    {
649
        $that = BigInteger::of($that);
650
 
651
        if ($that->value === '0' && $this->value[0] !== '-') {
652
            return $this;
653
        }
654
 
655
        if ($this->value === '0' && $that->value[0] !== '-') {
656
            return $that;
657
        }
658
 
659
        $value = Calculator::get()->gcd($this->value, $that->value);
660
 
661
        return new BigInteger($value);
662
    }
663
 
664
    /**
665
     * Returns the integer square root number of this number, rounded down.
666
     *
667
     * The result is the largest x such that x² ≤ n.
668
     *
669
     * @throws NegativeNumberException If this number is negative.
670
     */
671
    public function sqrt() : BigInteger
672
    {
673
        if ($this->value[0] === '-') {
674
            throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
675
        }
676
 
677
        $value = Calculator::get()->sqrt($this->value);
678
 
679
        return new BigInteger($value);
680
    }
681
 
682
    /**
683
     * Returns the absolute value of this number.
684
     */
685
    public function abs() : BigInteger
686
    {
687
        return $this->isNegative() ? $this->negated() : $this;
688
    }
689
 
690
    /**
691
     * Returns the inverse of this number.
692
     */
693
    public function negated() : BigInteger
694
    {
695
        return new BigInteger(Calculator::get()->neg($this->value));
696
    }
697
 
698
    /**
699
     * Returns the integer bitwise-and combined with another integer.
700
     *
701
     * This method returns a negative BigInteger if and only if both operands are negative.
702
     *
703
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
704
     */
399 lars 705
    public function and(BigNumber|int|float|string $that) : BigInteger
148 lars 706
    {
707
        $that = BigInteger::of($that);
708
 
709
        return new BigInteger(Calculator::get()->and($this->value, $that->value));
710
    }
711
 
712
    /**
713
     * Returns the integer bitwise-or combined with another integer.
714
     *
715
     * This method returns a negative BigInteger if and only if either of the operands is negative.
716
     *
717
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
718
     */
399 lars 719
    public function or(BigNumber|int|float|string $that) : BigInteger
148 lars 720
    {
721
        $that = BigInteger::of($that);
722
 
723
        return new BigInteger(Calculator::get()->or($this->value, $that->value));
724
    }
725
 
726
    /**
727
     * Returns the integer bitwise-xor combined with another integer.
728
     *
729
     * This method returns a negative BigInteger if and only if exactly one of the operands is negative.
730
     *
731
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
732
     */
399 lars 733
    public function xor(BigNumber|int|float|string $that) : BigInteger
148 lars 734
    {
735
        $that = BigInteger::of($that);
736
 
737
        return new BigInteger(Calculator::get()->xor($this->value, $that->value));
738
    }
739
 
740
    /**
741
     * Returns the bitwise-not of this BigInteger.
742
     */
743
    public function not() : BigInteger
744
    {
745
        return $this->negated()->minus(1);
746
    }
747
 
748
    /**
749
     * Returns the integer left shifted by a given number of bits.
750
     */
751
    public function shiftedLeft(int $distance) : BigInteger
752
    {
753
        if ($distance === 0) {
754
            return $this;
755
        }
756
 
757
        if ($distance < 0) {
758
            return $this->shiftedRight(- $distance);
759
        }
760
 
761
        return $this->multipliedBy(BigInteger::of(2)->power($distance));
762
    }
763
 
764
    /**
765
     * Returns the integer right shifted by a given number of bits.
766
     */
767
    public function shiftedRight(int $distance) : BigInteger
768
    {
769
        if ($distance === 0) {
770
            return $this;
771
        }
772
 
773
        if ($distance < 0) {
774
            return $this->shiftedLeft(- $distance);
775
        }
776
 
777
        $operand = BigInteger::of(2)->power($distance);
778
 
779
        if ($this->isPositiveOrZero()) {
780
            return $this->quotient($operand);
781
        }
782
 
783
        return $this->dividedBy($operand, RoundingMode::UP);
784
    }
785
 
786
    /**
787
     * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
788
     *
789
     * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation.
790
     * Computes (ceil(log2(this < 0 ? -this : this+1))).
791
     */
792
    public function getBitLength() : int
793
    {
794
        if ($this->value === '0') {
795
            return 0;
796
        }
797
 
798
        if ($this->isNegative()) {
799
            return $this->abs()->minus(1)->getBitLength();
800
        }
801
 
802
        return \strlen($this->toBase(2));
803
    }
804
 
805
    /**
806
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
807
     *
808
     * Returns -1 if this BigInteger contains no one bits.
809
     */
810
    public function getLowestSetBit() : int
811
    {
812
        $n = $this;
813
        $bitLength = $this->getBitLength();
814
 
815
        for ($i = 0; $i <= $bitLength; $i++) {
816
            if ($n->isOdd()) {
817
                return $i;
818
            }
819
 
820
            $n = $n->shiftedRight(1);
821
        }
822
 
823
        return -1;
824
    }
825
 
826
    /**
827
     * Returns whether this number is even.
828
     */
829
    public function isEven() : bool
830
    {
831
        return \in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
832
    }
833
 
834
    /**
835
     * Returns whether this number is odd.
836
     */
837
    public function isOdd() : bool
838
    {
839
        return \in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
840
    }
841
 
842
    /**
843
     * Returns true if and only if the designated bit is set.
844
     *
845
     * Computes ((this & (1<<n)) != 0).
846
     *
847
     * @param int $n The bit to test, 0-based.
848
     *
849
     * @throws \InvalidArgumentException If the bit to test is negative.
850
     */
851
    public function testBit(int $n) : bool
852
    {
853
        if ($n < 0) {
854
            throw new \InvalidArgumentException('The bit to test cannot be negative.');
855
        }
856
 
857
        return $this->shiftedRight($n)->isOdd();
858
    }
859
 
399 lars 860
    public function compareTo(BigNumber|int|float|string $that) : int
148 lars 861
    {
862
        $that = BigNumber::of($that);
863
 
864
        if ($that instanceof BigInteger) {
865
            return Calculator::get()->cmp($this->value, $that->value);
866
        }
867
 
868
        return - $that->compareTo($this);
869
    }
870
 
871
    public function getSign() : int
872
    {
873
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
874
    }
875
 
876
    public function toBigInteger() : BigInteger
877
    {
878
        return $this;
879
    }
880
 
881
    public function toBigDecimal() : BigDecimal
882
    {
399 lars 883
        return self::newBigDecimal($this->value);
148 lars 884
    }
885
 
886
    public function toBigRational() : BigRational
887
    {
399 lars 888
        return self::newBigRational($this, BigInteger::one(), false);
148 lars 889
    }
890
 
891
    public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal
892
    {
893
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
894
    }
895
 
896
    public function toInt() : int
897
    {
898
        $intValue = (int) $this->value;
899
 
900
        if ($this->value !== (string) $intValue) {
901
            throw IntegerOverflowException::toIntOverflow($this);
902
        }
903
 
904
        return $intValue;
905
    }
906
 
907
    public function toFloat() : float
908
    {
909
        return (float) $this->value;
910
    }
911
 
912
    /**
913
     * Returns a string representation of this number in the given base.
914
     *
915
     * The output will always be lowercase for bases greater than 10.
916
     *
917
     * @throws \InvalidArgumentException If the base is out of range.
918
     */
919
    public function toBase(int $base) : string
920
    {
921
        if ($base === 10) {
922
            return $this->value;
923
        }
924
 
925
        if ($base < 2 || $base > 36) {
926
            throw new \InvalidArgumentException(\sprintf('Base %d is out of range [2, 36]', $base));
927
        }
928
 
929
        return Calculator::get()->toBase($this->value, $base);
930
    }
931
 
932
    /**
933
     * Returns a string representation of this number in an arbitrary base with a custom alphabet.
934
     *
935
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers;
936
     * a NegativeNumberException will be thrown when attempting to call this method on a negative number.
937
     *
938
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
939
     *
940
     * @throws NegativeNumberException   If this number is negative.
941
     * @throws \InvalidArgumentException If the given alphabet does not contain at least 2 chars.
942
     */
943
    public function toArbitraryBase(string $alphabet) : string
944
    {
945
        $base = \strlen($alphabet);
946
 
947
        if ($base < 2) {
948
            throw new \InvalidArgumentException('The alphabet must contain at least 2 chars.');
949
        }
950
 
951
        if ($this->value[0] === '-') {
952
            throw new NegativeNumberException(__FUNCTION__ . '() does not support negative numbers.');
953
        }
954
 
955
        return Calculator::get()->toArbitraryBase($this->value, $alphabet, $base);
956
    }
957
 
958
    /**
959
     * Returns a string of bytes containing the binary representation of this BigInteger.
960
     *
961
     * The string is in big-endian byte-order: the most significant byte is in the zeroth element.
962
     *
963
     * If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to
964
     * the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the
965
     * number is negative.
966
     *
967
     * The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit
968
     * if `$signed` is true.
969
     *
970
     * This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match.
971
     *
972
     * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit.
973
     *
974
     * @throws NegativeNumberException If $signed is false, and the number is negative.
975
     */
976
    public function toBytes(bool $signed = true) : string
977
    {
978
        if (! $signed && $this->isNegative()) {
979
            throw new NegativeNumberException('Cannot convert a negative number to a byte string when $signed is false.');
980
        }
981
 
982
        $hex = $this->abs()->toBase(16);
983
 
984
        if (\strlen($hex) % 2 !== 0) {
985
            $hex = '0' . $hex;
986
        }
987
 
988
        $baseHexLength = \strlen($hex);
989
 
990
        if ($signed) {
991
            if ($this->isNegative()) {
992
                $bin = \hex2bin($hex);
993
                assert($bin !== false);
994
 
995
                $hex = \bin2hex(~$bin);
996
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
997
 
998
                $hexLength = \strlen($hex);
999
 
1000
                if ($hexLength < $baseHexLength) {
1001
                    $hex = \str_repeat('0', $baseHexLength - $hexLength) . $hex;
1002
                }
1003
 
1004
                if ($hex[0] < '8') {
1005
                    $hex = 'FF' . $hex;
1006
                }
1007
            } else {
1008
                if ($hex[0] >= '8') {
1009
                    $hex = '00' . $hex;
1010
                }
1011
            }
1012
        }
1013
 
1014
        return \hex2bin($hex);
1015
    }
1016
 
1017
    public function __toString() : string
1018
    {
1019
        return $this->value;
1020
    }
1021
 
1022
    /**
1023
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1024
     *
1025
     * @internal
1026
     *
1027
     * @return array{value: string}
1028
     */
1029
    public function __serialize(): array
1030
    {
1031
        return ['value' => $this->value];
1032
    }
1033
 
1034
    /**
1035
     * This method is only here to allow unserializing the object and cannot be accessed directly.
1036
     *
1037
     * @internal
1038
     * @psalm-suppress RedundantPropertyInitializationCheck
1039
     *
1040
     * @param array{value: string} $data
1041
     *
1042
     * @throws \LogicException
1043
     */
1044
    public function __unserialize(array $data): void
1045
    {
1046
        if (isset($this->value)) {
1047
            throw new \LogicException('__unserialize() is an internal function, it must not be called directly.');
1048
        }
1049
 
1050
        $this->value = $data['value'];
1051
    }
1052
 
1053
    /**
1054
     * This method is required by interface Serializable and SHOULD NOT be accessed directly.
1055
     *
1056
     * @internal
1057
     */
1058
    public function serialize() : string
1059
    {
1060
        return $this->value;
1061
    }
1062
 
1063
    /**
1064
     * This method is only here to implement interface Serializable and cannot be accessed directly.
1065
     *
1066
     * @internal
1067
     * @psalm-suppress RedundantPropertyInitializationCheck
1068
     *
1069
     * @throws \LogicException
1070
     */
1071
    public function unserialize($value) : void
1072
    {
1073
        if (isset($this->value)) {
1074
            throw new \LogicException('unserialize() is an internal function, it must not be called directly.');
1075
        }
1076
 
1077
        $this->value = $value;
1078
    }
1079
}