Debian Codegraph @

lib/3rdParty/composer/brick/math/src/Internal/Calculator/NativeCalculator.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Brick\Math\Internal\Calculator;
6
7 use Brick\Math\Internal\Calculator;
8 use Override;
9
10 /**
11 * Calculator implementation using only native PHP code.
12 *
13 * @internal
14 *
15 * @psalm-immutable
16 */
17 class NativeCalculator extends Calculator
18 {
19 /**
20 * The max number of digits the platform can natively add, subtract, multiply or divide without overflow.
21 * For multiplication, this represents the max sum of the lengths of both operands.
22 *
23 * In addition, it is assumed that an extra digit can hold a carry (1) without overflowing.
24 * Example: 32-bit: max number 1,999,999,999 (9 digits + carry)
25 * 64-bit: max number 1,999,999,999,999,999,999 (18 digits + carry)
26 */
27 private readonly int $maxDigits;
28
29 /**
30 * @codeCoverageIgnore
31 */
32 public function __construct()
33 {
34 $this->maxDigits = match (PHP_INT_SIZE) {
35 4 => 9,
36 8 => 18,
37 default => throw new \RuntimeException('The platform is not 32-bit or 64-bit as expected.')
38 };
39 }
40
41 #[Override]
42 public function add(string $a, string $b) : string
43 {
44 /**
45 * @psalm-var numeric-string $a
46 * @psalm-var numeric-string $b
47 */
48 $result = $a + $b;
49
50 if (is_int($result)) {
51 return (string) $result;
52 }
53
54 if ($a === '0') {
55 return $b;
56 }
57
58 if ($b === '0') {
59 return $a;
60 }
61
62 [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
63
64 $result = $aNeg === $bNeg ? $this->doAdd($aDig, $bDig) : $this->doSub($aDig, $bDig);
65
66 if ($aNeg) {
67 $result = $this->neg($result);
68 }
69
70 return $result;
71 }
72
73 #[Override]
74 public function sub(string $a, string $b) : string
75 {
76 return $this->add($a, $this->neg($b));
77 }
78
79 #[Override]
80 public function mul(string $a, string $b) : string
81 {
82 /**
83 * @psalm-var numeric-string $a
84 * @psalm-var numeric-string $b
85 */
86 $result = $a * $b;
87
88 if (is_int($result)) {
89 return (string) $result;
90 }
91
92 if ($a === '0' || $b === '0') {
93 return '0';
94 }
95
96 if ($a === '1') {
97 return $b;
98 }
99
100 if ($b === '1') {
101 return $a;
102 }
103
104 if ($a === '-1') {
105 return $this->neg($b);
106 }
107
108 if ($b === '-1') {
109 return $this->neg($a);
110 }
111
112 [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
113
114 $result = $this->doMul($aDig, $bDig);
115
116 if ($aNeg !== $bNeg) {
117 $result = $this->neg($result);
118 }
119
120 return $result;
121 }
122
123 #[Override]
124 public function divQ(string $a, string $b) : string
125 {
126 return $this->divQR($a, $b)[0];
127 }
128
129 #[Override]
130 public function divR(string $a, string $b): string
131 {
132 return $this->divQR($a, $b)[1];
133 }
134
135 #[Override]
136 public function divQR(string $a, string $b) : array
137 {
138 if ($a === '0') {
139 return ['0', '0'];
140 }
141
142 if ($a === $b) {
143 return ['1', '0'];
144 }
145
146 if ($b === '1') {
147 return [$a, '0'];
148 }
149
150 if ($b === '-1') {
151 return [$this->neg($a), '0'];
152 }
153
154 /** @psalm-var numeric-string $a */
155 $na = $a * 1; // cast to number
156
157 if (is_int($na)) {
158 /** @psalm-var numeric-string $b */
159 $nb = $b * 1;
160
161 if (is_int($nb)) {
162 // the only division that may overflow is PHP_INT_MIN / -1,
163 // which cannot happen here as we've already handled a divisor of -1 above.
164 $q = intdiv($na, $nb);
165 $r = $na % $nb;
166
167 return [
168 (string) $q,
169 (string) $r
170 ];
171 }
172 }
173
174 [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
175
176 [$q, $r] = $this->doDiv($aDig, $bDig);
177
178 if ($aNeg !== $bNeg) {
179 $q = $this->neg($q);
180 }
181
182 if ($aNeg) {
183 $r = $this->neg($r);
184 }
185
186 return [$q, $r];
187 }
188
189 #[Override]
190 public function pow(string $a, int $e) : string
191 {
192 if ($e === 0) {
193 return '1';
194 }
195
196 if ($e === 1) {
197 return $a;
198 }
199
200 $odd = $e % 2;
201 $e -= $odd;
202
203 $aa = $this->mul($a, $a);
204
205 /** @psalm-suppress PossiblyInvalidArgument We're sure that $e / 2 is an int now */
206 $result = $this->pow($aa, $e / 2);
207
208 if ($odd === 1) {
209 $result = $this->mul($result, $a);
210 }
211
212 return $result;
213 }
214
215 /**
216 * Algorithm from: https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/
217 */
218 #[Override]
219 public function modPow(string $base, string $exp, string $mod) : string
220 {
221 // special case: the algorithm below fails with 0 power 0 mod 1 (returns 1 instead of 0)
222 if ($base === '0' && $exp === '0' && $mod === '1') {
223 return '0';
224 }
225
226 // special case: the algorithm below fails with power 0 mod 1 (returns 1 instead of 0)
227 if ($exp === '0' && $mod === '1') {
228 return '0';
229 }
230
231 $x = $base;
232
233 $res = '1';
234
235 // numbers are positive, so we can use remainder instead of modulo
236 $x = $this->divR($x, $mod);
237
238 while ($exp !== '0') {
239 if (in_array($exp[-1], ['1', '3', '5', '7', '9'])) { // odd
240 $res = $this->divR($this->mul($res, $x), $mod);
241 }
242
243 $exp = $this->divQ($exp, '2');
244 $x = $this->divR($this->mul($x, $x), $mod);
245 }
246
247 return $res;
248 }
249
250 /**
251 * Adapted from https://cp-algorithms.com/num_methods/roots_newton.html
252 */
253 #[Override]
254 public function sqrt(string $n) : string
255 {
256 if ($n === '0') {
257 return '0';
258 }
259
260 // initial approximation
261 $x = \str_repeat('9', \intdiv(\strlen($n), 2) ?: 1);
262
263 $decreased = false;
264
265 for (;;) {
266 $nx = $this->divQ($this->add($x, $this->divQ($n, $x)), '2');
267
268 if ($x === $nx || $this->cmp($nx, $x) > 0 && $decreased) {
269 break;
270 }
271
272 $decreased = $this->cmp($nx, $x) < 0;
273 $x = $nx;
274 }
275
276 return $x;
277 }
278
279 /**
280 * Performs the addition of two non-signed large integers.
281 */
282 private function doAdd(string $a, string $b) : string
283 {
284 [$a, $b, $length] = $this->pad($a, $b);
285
286 $carry = 0;
287 $result = '';
288
289 for ($i = $length - $this->maxDigits;; $i -= $this->maxDigits) {
290 $blockLength = $this->maxDigits;
291
292 if ($i < 0) {
293 $blockLength += $i;
294 /** @psalm-suppress LoopInvalidation */
295 $i = 0;
296 }
297
298 /** @psalm-var numeric-string $blockA */
299 $blockA = \substr($a, $i, $blockLength);
300
301 /** @psalm-var numeric-string $blockB */
302 $blockB = \substr($b, $i, $blockLength);
303
304 $sum = (string) ($blockA + $blockB + $carry);
305 $sumLength = \strlen($sum);
306
307 if ($sumLength > $blockLength) {
308 $sum = \substr($sum, 1);
309 $carry = 1;
310 } else {
311 if ($sumLength < $blockLength) {
312 $sum = \str_repeat('0', $blockLength - $sumLength) . $sum;
313 }
314 $carry = 0;
315 }
316
317 $result = $sum . $result;
318
319 if ($i === 0) {
320 break;
321 }
322 }
323
324 if ($carry === 1) {
325 $result = '1' . $result;
326 }
327
328 return $result;
329 }
330
331 /**
332 * Performs the subtraction of two non-signed large integers.
333 */
334 private function doSub(string $a, string $b) : string
335 {
336 if ($a === $b) {
337 return '0';
338 }
339
340 // Ensure that we always subtract to a positive result: biggest minus smallest.
341 $cmp = $this->doCmp($a, $b);
342
343 $invert = ($cmp === -1);
344
345 if ($invert) {
346 $c = $a;
347 $a = $b;
348 $b = $c;
349 }
350
351 [$a, $b, $length] = $this->pad($a, $b);
352
353 $carry = 0;
354 $result = '';
355
356 $complement = 10 ** $this->maxDigits;
357
358 for ($i = $length - $this->maxDigits;; $i -= $this->maxDigits) {
359 $blockLength = $this->maxDigits;
360
361 if ($i < 0) {
362 $blockLength += $i;
363 /** @psalm-suppress LoopInvalidation */
364 $i = 0;
365 }
366
367 /** @psalm-var numeric-string $blockA */
368 $blockA = \substr($a, $i, $blockLength);
369
370 /** @psalm-var numeric-string $blockB */
371 $blockB = \substr($b, $i, $blockLength);
372
373 $sum = $blockA - $blockB - $carry;
374
375 if ($sum < 0) {
376 $sum += $complement;
377 $carry = 1;
378 } else {
379 $carry = 0;
380 }
381
382 $sum = (string) $sum;
383 $sumLength = \strlen($sum);
384
385 if ($sumLength < $blockLength) {
386 $sum = \str_repeat('0', $blockLength - $sumLength) . $sum;
387 }
388
389 $result = $sum . $result;
390
391 if ($i === 0) {
392 break;
393 }
394 }
395
396 // Carry cannot be 1 when the loop ends, as a > b
397 assert($carry === 0);
398
399 $result = \ltrim($result, '0');
400
401 if ($invert) {
402 $result = $this->neg($result);
403 }
404
405 return $result;
406 }
407
408 /**
409 * Performs the multiplication of two non-signed large integers.
410 */
411 private function doMul(string $a, string $b) : string
412 {
413 $x = \strlen($a);
414 $y = \strlen($b);
415
416 $maxDigits = \intdiv($this->maxDigits, 2);
417 $complement = 10 ** $maxDigits;
418
419 $result = '0';
420
421 for ($i = $x - $maxDigits;; $i -= $maxDigits) {
422 $blockALength = $maxDigits;
423
424 if ($i < 0) {
425 $blockALength += $i;
426 /** @psalm-suppress LoopInvalidation */
427 $i = 0;
428 }
429
430 $blockA = (int) \substr($a, $i, $blockALength);
431
432 $line = '';
433 $carry = 0;
434
435 for ($j = $y - $maxDigits;; $j -= $maxDigits) {
436 $blockBLength = $maxDigits;
437
438 if ($j < 0) {
439 $blockBLength += $j;
440 /** @psalm-suppress LoopInvalidation */
441 $j = 0;
442 }
443
444 $blockB = (int) \substr($b, $j, $blockBLength);
445
446 $mul = $blockA * $blockB + $carry;
447 $value = $mul % $complement;
448 $carry = ($mul - $value) / $complement;
449
450 $value = (string) $value;
451 $value = \str_pad($value, $maxDigits, '0', STR_PAD_LEFT);
452
453 $line = $value . $line;
454
455 if ($j === 0) {
456 break;
457 }
458 }
459
460 if ($carry !== 0) {
461 $line = $carry . $line;
462 }
463
464 $line = \ltrim($line, '0');
465
466 if ($line !== '') {
467 $line .= \str_repeat('0', $x - $blockALength - $i);
468 $result = $this->add($result, $line);
469 }
470
471 if ($i === 0) {
472 break;
473 }
474 }
475
476 return $result;
477 }
478
479 /**
480 * Performs the division of two non-signed large integers.
481 *
482 * @return string[] The quotient and remainder.
483 */
484 private function doDiv(string $a, string $b) : array
485 {
486 $cmp = $this->doCmp($a, $b);
487
488 if ($cmp === -1) {
489 return ['0', $a];
490 }
491
492 $x = \strlen($a);
493 $y = \strlen($b);
494
495 // we now know that a >= b && x >= y
496
497 $q = '0'; // quotient
498 $r = $a; // remainder
499 $z = $y; // focus length, always $y or $y+1
500
501 /** @psalm-var numeric-string $b */
502 $nb = $b * 1; // cast to number
503 // performance optimization in cases where the remainder will never cause int overflow
504 if (is_int(($nb - 1) * 10 + 9)) {
505 $r = (int) \substr($a, 0, $z - 1);
506
507 for ($i = $z - 1; $i < $x; $i++) {
508 $n = $r * 10 + (int) $a[$i];
509 /** @psalm-var int $nb */
510 $q .= \intdiv($n, $nb);
511 $r = $n % $nb;
512 }
513
514 return [\ltrim($q, '0') ?: '0', (string) $r];
515 }
516
517 for (;;) {
518 $focus = \substr($a, 0, $z);
519
520 $cmp = $this->doCmp($focus, $b);
521
522 if ($cmp === -1) {
523 if ($z === $x) { // remainder < dividend
524 break;
525 }
526
527 $z++;
528 }
529
530 $zeros = \str_repeat('0', $x - $z);
531
532 $q = $this->add($q, '1' . $zeros);
533 $a = $this->sub($a, $b . $zeros);
534
535 $r = $a;
536
537 if ($r === '0') { // remainder == 0
538 break;
539 }
540
541 $x = \strlen($a);
542
543 if ($x < $y) { // remainder < dividend
544 break;
545 }
546
547 $z = $y;
548 }
549
550 return [$q, $r];
551 }
552
553 /**
554 * Compares two non-signed large numbers.
555 *
556 * @psalm-return -1|0|1
557 */
558 private function doCmp(string $a, string $b) : int
559 {
560 $x = \strlen($a);
561 $y = \strlen($b);
562
563 $cmp = $x <=> $y;
564
565 if ($cmp !== 0) {
566 return $cmp;
567 }
568
569 return \strcmp($a, $b) <=> 0; // enforce -1|0|1
570 }
571
572 /**
573 * Pads the left of one of the given numbers with zeros if necessary to make both numbers the same length.
574 *
575 * The numbers must only consist of digits, without leading minus sign.
576 *
577 * @return array{string, string, int}
578 */
579 private function pad(string $a, string $b) : array
580 {
581 $x = \strlen($a);
582 $y = \strlen($b);
583
584 if ($x > $y) {
585 $b = \str_repeat('0', $x - $y) . $b;
586
587 return [$a, $b, $x];
588 }
589
590 if ($x < $y) {
591 $a = \str_repeat('0', $y - $x) . $a;
592
593 return [$a, $b, $y];
594 }
595
596 return [$a, $b, $x];
597 }
598 }