Calculator.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. <?php
  2. declare(strict_types=1);
  3. namespace Brick\Math\Internal;
  4. use Brick\Math\Exception\RoundingNecessaryException;
  5. use Brick\Math\RoundingMode;
  6. /**
  7. * Performs basic operations on arbitrary size integers.
  8. *
  9. * Unless otherwise specified, all parameters must be validated as non-empty strings of digits,
  10. * without leading zero, and with an optional leading minus sign if the number is not zero.
  11. *
  12. * Any other parameter format will lead to undefined behaviour.
  13. * All methods must return strings respecting this format, unless specified otherwise.
  14. *
  15. * @internal
  16. *
  17. * @psalm-immutable
  18. */
  19. abstract class Calculator
  20. {
  21. /**
  22. * The maximum exponent value allowed for the pow() method.
  23. */
  24. public const MAX_POWER = 1000000;
  25. /**
  26. * The alphabet for converting from and to base 2 to 36, lowercase.
  27. */
  28. public const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
  29. /**
  30. * The Calculator instance in use.
  31. *
  32. * @var Calculator|null
  33. */
  34. private static $instance;
  35. /**
  36. * Sets the Calculator instance to use.
  37. *
  38. * An instance is typically set only in unit tests: the autodetect is usually the best option.
  39. *
  40. * @param Calculator|null $calculator The calculator instance, or NULL to revert to autodetect.
  41. *
  42. * @return void
  43. */
  44. final public static function set(?Calculator $calculator) : void
  45. {
  46. self::$instance = $calculator;
  47. }
  48. /**
  49. * Returns the Calculator instance to use.
  50. *
  51. * If none has been explicitly set, the fastest available implementation will be returned.
  52. *
  53. * @return Calculator
  54. *
  55. * @psalm-pure
  56. * @psalm-suppress ImpureStaticProperty
  57. */
  58. final public static function get() : Calculator
  59. {
  60. if (self::$instance === null) {
  61. /** @psalm-suppress ImpureMethodCall */
  62. self::$instance = self::detect();
  63. }
  64. return self::$instance;
  65. }
  66. /**
  67. * Returns the fastest available Calculator implementation.
  68. *
  69. * @codeCoverageIgnore
  70. *
  71. * @return Calculator
  72. */
  73. private static function detect() : Calculator
  74. {
  75. if (\extension_loaded('gmp')) {
  76. return new Calculator\GmpCalculator();
  77. }
  78. if (\extension_loaded('bcmath')) {
  79. return new Calculator\BcMathCalculator();
  80. }
  81. return new Calculator\NativeCalculator();
  82. }
  83. /**
  84. * Extracts the sign & digits of the operands.
  85. *
  86. * @param string $a The first operand.
  87. * @param string $b The second operand.
  88. *
  89. * @return array{0: bool, 1: bool, 2: string, 3: string} Whether $a and $b are negative, followed by their digits.
  90. */
  91. final protected function init(string $a, string $b) : array
  92. {
  93. return [
  94. $aNeg = ($a[0] === '-'),
  95. $bNeg = ($b[0] === '-'),
  96. $aNeg ? \substr($a, 1) : $a,
  97. $bNeg ? \substr($b, 1) : $b,
  98. ];
  99. }
  100. /**
  101. * Returns the absolute value of a number.
  102. *
  103. * @param string $n The number.
  104. *
  105. * @return string The absolute value.
  106. */
  107. final public function abs(string $n) : string
  108. {
  109. return ($n[0] === '-') ? \substr($n, 1) : $n;
  110. }
  111. /**
  112. * Negates a number.
  113. *
  114. * @param string $n The number.
  115. *
  116. * @return string The negated value.
  117. */
  118. final public function neg(string $n) : string
  119. {
  120. if ($n === '0') {
  121. return '0';
  122. }
  123. if ($n[0] === '-') {
  124. return \substr($n, 1);
  125. }
  126. return '-' . $n;
  127. }
  128. /**
  129. * Compares two numbers.
  130. *
  131. * @param string $a The first number.
  132. * @param string $b The second number.
  133. *
  134. * @return int [-1, 0, 1] If the first number is less than, equal to, or greater than the second number.
  135. */
  136. final public function cmp(string $a, string $b) : int
  137. {
  138. [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
  139. if ($aNeg && ! $bNeg) {
  140. return -1;
  141. }
  142. if ($bNeg && ! $aNeg) {
  143. return 1;
  144. }
  145. $aLen = \strlen($aDig);
  146. $bLen = \strlen($bDig);
  147. if ($aLen < $bLen) {
  148. $result = -1;
  149. } elseif ($aLen > $bLen) {
  150. $result = 1;
  151. } else {
  152. $result = $aDig <=> $bDig;
  153. }
  154. return $aNeg ? -$result : $result;
  155. }
  156. /**
  157. * Adds two numbers.
  158. *
  159. * @param string $a The augend.
  160. * @param string $b The addend.
  161. *
  162. * @return string The sum.
  163. */
  164. abstract public function add(string $a, string $b) : string;
  165. /**
  166. * Subtracts two numbers.
  167. *
  168. * @param string $a The minuend.
  169. * @param string $b The subtrahend.
  170. *
  171. * @return string The difference.
  172. */
  173. abstract public function sub(string $a, string $b) : string;
  174. /**
  175. * Multiplies two numbers.
  176. *
  177. * @param string $a The multiplicand.
  178. * @param string $b The multiplier.
  179. *
  180. * @return string The product.
  181. */
  182. abstract public function mul(string $a, string $b) : string;
  183. /**
  184. * Returns the quotient of the division of two numbers.
  185. *
  186. * @param string $a The dividend.
  187. * @param string $b The divisor, must not be zero.
  188. *
  189. * @return string The quotient.
  190. */
  191. abstract public function divQ(string $a, string $b) : string;
  192. /**
  193. * Returns the remainder of the division of two numbers.
  194. *
  195. * @param string $a The dividend.
  196. * @param string $b The divisor, must not be zero.
  197. *
  198. * @return string The remainder.
  199. */
  200. abstract public function divR(string $a, string $b) : string;
  201. /**
  202. * Returns the quotient and remainder of the division of two numbers.
  203. *
  204. * @param string $a The dividend.
  205. * @param string $b The divisor, must not be zero.
  206. *
  207. * @return string[] An array containing the quotient and remainder.
  208. */
  209. abstract public function divQR(string $a, string $b) : array;
  210. /**
  211. * Exponentiates a number.
  212. *
  213. * @param string $a The base number.
  214. * @param int $e The exponent, validated as an integer between 0 and MAX_POWER.
  215. *
  216. * @return string The power.
  217. */
  218. abstract public function pow(string $a, int $e) : string;
  219. /**
  220. * @param string $a
  221. * @param string $b The modulus; must not be zero.
  222. *
  223. * @return string
  224. */
  225. public function mod(string $a, string $b) : string
  226. {
  227. return $this->divR($this->add($this->divR($a, $b), $b), $b);
  228. }
  229. /**
  230. * Returns the modular multiplicative inverse of $x modulo $m.
  231. *
  232. * If $x has no multiplicative inverse mod m, this method must return null.
  233. *
  234. * This method can be overridden by the concrete implementation if the underlying library has built-in support.
  235. *
  236. * @param string $x
  237. * @param string $m The modulus; must not be negative or zero.
  238. *
  239. * @return string|null
  240. */
  241. public function modInverse(string $x, string $m) : ?string
  242. {
  243. if ($m === '1') {
  244. return '0';
  245. }
  246. $modVal = $x;
  247. if ($x[0] === '-' || ($this->cmp($this->abs($x), $m) >= 0)) {
  248. $modVal = $this->mod($x, $m);
  249. }
  250. $x = '0';
  251. $y = '0';
  252. $g = $this->gcdExtended($modVal, $m, $x, $y);
  253. if ($g !== '1') {
  254. return null;
  255. }
  256. return $this->mod($this->add($this->mod($x, $m), $m), $m);
  257. }
  258. /**
  259. * Raises a number into power with modulo.
  260. *
  261. * @param string $base The base number; must be positive or zero.
  262. * @param string $exp The exponent; must be positive or zero.
  263. * @param string $mod The modulus; must be strictly positive.
  264. *
  265. * @return string The power.
  266. */
  267. abstract public function modPow(string $base, string $exp, string $mod) : string;
  268. /**
  269. * Returns the greatest common divisor of the two numbers.
  270. *
  271. * This method can be overridden by the concrete implementation if the underlying library
  272. * has built-in support for GCD calculations.
  273. *
  274. * @param string $a The first number.
  275. * @param string $b The second number.
  276. *
  277. * @return string The GCD, always positive, or zero if both arguments are zero.
  278. */
  279. public function gcd(string $a, string $b) : string
  280. {
  281. if ($a === '0') {
  282. return $this->abs($b);
  283. }
  284. if ($b === '0') {
  285. return $this->abs($a);
  286. }
  287. return $this->gcd($b, $this->divR($a, $b));
  288. }
  289. private function gcdExtended(string $a, string $b, string &$x, string &$y) : string
  290. {
  291. if ($a === '0') {
  292. $x = '0';
  293. $y = '1';
  294. return $b;
  295. }
  296. $x1 = '0';
  297. $y1 = '0';
  298. $gcd = $this->gcdExtended($this->mod($b, $a), $a, $x1, $y1);
  299. $x = $this->sub($y1, $this->mul($this->divQ($b, $a), $x1));
  300. $y = $x1;
  301. return $gcd;
  302. }
  303. /**
  304. * Returns the square root of the given number, rounded down.
  305. *
  306. * The result is the largest x such that x² ≤ n.
  307. * The input MUST NOT be negative.
  308. *
  309. * @param string $n The number.
  310. *
  311. * @return string The square root.
  312. */
  313. abstract public function sqrt(string $n) : string;
  314. /**
  315. * Converts a number from an arbitrary base.
  316. *
  317. * This method can be overridden by the concrete implementation if the underlying library
  318. * has built-in support for base conversion.
  319. *
  320. * @param string $number The number, positive or zero, non-empty, case-insensitively validated for the given base.
  321. * @param int $base The base of the number, validated from 2 to 36.
  322. *
  323. * @return string The converted number, following the Calculator conventions.
  324. */
  325. public function fromBase(string $number, int $base) : string
  326. {
  327. return $this->fromArbitraryBase(\strtolower($number), self::ALPHABET, $base);
  328. }
  329. /**
  330. * Converts a number to an arbitrary base.
  331. *
  332. * This method can be overridden by the concrete implementation if the underlying library
  333. * has built-in support for base conversion.
  334. *
  335. * @param string $number The number to convert, following the Calculator conventions.
  336. * @param int $base The base to convert to, validated from 2 to 36.
  337. *
  338. * @return string The converted number, lowercase.
  339. */
  340. public function toBase(string $number, int $base) : string
  341. {
  342. $negative = ($number[0] === '-');
  343. if ($negative) {
  344. $number = \substr($number, 1);
  345. }
  346. $number = $this->toArbitraryBase($number, self::ALPHABET, $base);
  347. if ($negative) {
  348. return '-' . $number;
  349. }
  350. return $number;
  351. }
  352. /**
  353. * Converts a non-negative number in an arbitrary base using a custom alphabet, to base 10.
  354. *
  355. * @param string $number The number to convert, validated as a non-empty string,
  356. * containing only chars in the given alphabet/base.
  357. * @param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.
  358. * @param int $base The base of the number, validated from 2 to alphabet length.
  359. *
  360. * @return string The number in base 10, following the Calculator conventions.
  361. */
  362. final public function fromArbitraryBase(string $number, string $alphabet, int $base) : string
  363. {
  364. // remove leading "zeros"
  365. $number = \ltrim($number, $alphabet[0]);
  366. if ($number === '') {
  367. return '0';
  368. }
  369. // optimize for "one"
  370. if ($number === $alphabet[1]) {
  371. return '1';
  372. }
  373. $result = '0';
  374. $power = '1';
  375. $base = (string) $base;
  376. for ($i = \strlen($number) - 1; $i >= 0; $i--) {
  377. $index = \strpos($alphabet, $number[$i]);
  378. if ($index !== 0) {
  379. $result = $this->add($result, ($index === 1)
  380. ? $power
  381. : $this->mul($power, (string) $index)
  382. );
  383. }
  384. if ($i !== 0) {
  385. $power = $this->mul($power, $base);
  386. }
  387. }
  388. return $result;
  389. }
  390. /**
  391. * Converts a non-negative number to an arbitrary base using a custom alphabet.
  392. *
  393. * @param string $number The number to convert, positive or zero, following the Calculator conventions.
  394. * @param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.
  395. * @param int $base The base to convert to, validated from 2 to alphabet length.
  396. *
  397. * @return string The converted number in the given alphabet.
  398. */
  399. final public function toArbitraryBase(string $number, string $alphabet, int $base) : string
  400. {
  401. if ($number === '0') {
  402. return $alphabet[0];
  403. }
  404. $base = (string) $base;
  405. $result = '';
  406. while ($number !== '0') {
  407. [$number, $remainder] = $this->divQR($number, $base);
  408. $remainder = (int) $remainder;
  409. $result .= $alphabet[$remainder];
  410. }
  411. return \strrev($result);
  412. }
  413. /**
  414. * Performs a rounded division.
  415. *
  416. * Rounding is performed when the remainder of the division is not zero.
  417. *
  418. * @param string $a The dividend.
  419. * @param string $b The divisor, must not be zero.
  420. * @param int $roundingMode The rounding mode.
  421. *
  422. * @return string
  423. *
  424. * @throws \InvalidArgumentException If the rounding mode is invalid.
  425. * @throws RoundingNecessaryException If RoundingMode::UNNECESSARY is provided but rounding is necessary.
  426. */
  427. final public function divRound(string $a, string $b, int $roundingMode) : string
  428. {
  429. [$quotient, $remainder] = $this->divQR($a, $b);
  430. $hasDiscardedFraction = ($remainder !== '0');
  431. $isPositiveOrZero = ($a[0] === '-') === ($b[0] === '-');
  432. $discardedFractionSign = function() use ($remainder, $b) : int {
  433. $r = $this->abs($this->mul($remainder, '2'));
  434. $b = $this->abs($b);
  435. return $this->cmp($r, $b);
  436. };
  437. $increment = false;
  438. switch ($roundingMode) {
  439. case RoundingMode::UNNECESSARY:
  440. if ($hasDiscardedFraction) {
  441. throw RoundingNecessaryException::roundingNecessary();
  442. }
  443. break;
  444. case RoundingMode::UP:
  445. $increment = $hasDiscardedFraction;
  446. break;
  447. case RoundingMode::DOWN:
  448. break;
  449. case RoundingMode::CEILING:
  450. $increment = $hasDiscardedFraction && $isPositiveOrZero;
  451. break;
  452. case RoundingMode::FLOOR:
  453. $increment = $hasDiscardedFraction && ! $isPositiveOrZero;
  454. break;
  455. case RoundingMode::HALF_UP:
  456. $increment = $discardedFractionSign() >= 0;
  457. break;
  458. case RoundingMode::HALF_DOWN:
  459. $increment = $discardedFractionSign() > 0;
  460. break;
  461. case RoundingMode::HALF_CEILING:
  462. $increment = $isPositiveOrZero ? $discardedFractionSign() >= 0 : $discardedFractionSign() > 0;
  463. break;
  464. case RoundingMode::HALF_FLOOR:
  465. $increment = $isPositiveOrZero ? $discardedFractionSign() > 0 : $discardedFractionSign() >= 0;
  466. break;
  467. case RoundingMode::HALF_EVEN:
  468. $lastDigit = (int) $quotient[-1];
  469. $lastDigitIsEven = ($lastDigit % 2 === 0);
  470. $increment = $lastDigitIsEven ? $discardedFractionSign() > 0 : $discardedFractionSign() >= 0;
  471. break;
  472. default:
  473. throw new \InvalidArgumentException('Invalid rounding mode.');
  474. }
  475. if ($increment) {
  476. return $this->add($quotient, $isPositiveOrZero ? '1' : '-1');
  477. }
  478. return $quotient;
  479. }
  480. /**
  481. * Calculates bitwise AND of two numbers.
  482. *
  483. * This method can be overridden by the concrete implementation if the underlying library
  484. * has built-in support for bitwise operations.
  485. *
  486. * @param string $a
  487. * @param string $b
  488. *
  489. * @return string
  490. */
  491. public function and(string $a, string $b) : string
  492. {
  493. return $this->bitwise('and', $a, $b);
  494. }
  495. /**
  496. * Calculates bitwise OR of two numbers.
  497. *
  498. * This method can be overridden by the concrete implementation if the underlying library
  499. * has built-in support for bitwise operations.
  500. *
  501. * @param string $a
  502. * @param string $b
  503. *
  504. * @return string
  505. */
  506. public function or(string $a, string $b) : string
  507. {
  508. return $this->bitwise('or', $a, $b);
  509. }
  510. /**
  511. * Calculates bitwise XOR of two numbers.
  512. *
  513. * This method can be overridden by the concrete implementation if the underlying library
  514. * has built-in support for bitwise operations.
  515. *
  516. * @param string $a
  517. * @param string $b
  518. *
  519. * @return string
  520. */
  521. public function xor(string $a, string $b) : string
  522. {
  523. return $this->bitwise('xor', $a, $b);
  524. }
  525. /**
  526. * Performs a bitwise operation on a decimal number.
  527. *
  528. * @param string $operator The operator to use, must be "and", "or" or "xor".
  529. * @param string $a The left operand.
  530. * @param string $b The right operand.
  531. *
  532. * @return string
  533. */
  534. private function bitwise(string $operator, string $a, string $b) : string
  535. {
  536. [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
  537. $aBin = $this->toBinary($aDig);
  538. $bBin = $this->toBinary($bDig);
  539. $aLen = \strlen($aBin);
  540. $bLen = \strlen($bBin);
  541. if ($aLen > $bLen) {
  542. $bBin = \str_repeat("\x00", $aLen - $bLen) . $bBin;
  543. } elseif ($bLen > $aLen) {
  544. $aBin = \str_repeat("\x00", $bLen - $aLen) . $aBin;
  545. }
  546. if ($aNeg) {
  547. $aBin = $this->twosComplement($aBin);
  548. }
  549. if ($bNeg) {
  550. $bBin = $this->twosComplement($bBin);
  551. }
  552. switch ($operator) {
  553. case 'and':
  554. $value = $aBin & $bBin;
  555. $negative = ($aNeg and $bNeg);
  556. break;
  557. case 'or':
  558. $value = $aBin | $bBin;
  559. $negative = ($aNeg or $bNeg);
  560. break;
  561. case 'xor':
  562. $value = $aBin ^ $bBin;
  563. $negative = ($aNeg xor $bNeg);
  564. break;
  565. // @codeCoverageIgnoreStart
  566. default:
  567. throw new \InvalidArgumentException('Invalid bitwise operator.');
  568. // @codeCoverageIgnoreEnd
  569. }
  570. if ($negative) {
  571. $value = $this->twosComplement($value);
  572. }
  573. $result = $this->toDecimal($value);
  574. return $negative ? $this->neg($result) : $result;
  575. }
  576. /**
  577. * @param string $number A positive, binary number.
  578. *
  579. * @return string
  580. */
  581. private function twosComplement(string $number) : string
  582. {
  583. $xor = \str_repeat("\xff", \strlen($number));
  584. $number = $number ^ $xor;
  585. for ($i = \strlen($number) - 1; $i >= 0; $i--) {
  586. $byte = \ord($number[$i]);
  587. if (++$byte !== 256) {
  588. $number[$i] = \chr($byte);
  589. break;
  590. }
  591. $number[$i] = "\x00";
  592. if ($i === 0) {
  593. $number = "\x01" . $number;
  594. }
  595. }
  596. return $number;
  597. }
  598. /**
  599. * Converts a decimal number to a binary string.
  600. *
  601. * @param string $number The number to convert, positive or zero, only digits.
  602. *
  603. * @return string
  604. */
  605. private function toBinary(string $number) : string
  606. {
  607. $result = '';
  608. while ($number !== '0') {
  609. [$number, $remainder] = $this->divQR($number, '256');
  610. $result .= \chr((int) $remainder);
  611. }
  612. return \strrev($result);
  613. }
  614. /**
  615. * Returns the positive decimal representation of a binary number.
  616. *
  617. * @param string $bytes The bytes representing the number.
  618. *
  619. * @return string
  620. */
  621. private function toDecimal(string $bytes) : string
  622. {
  623. $result = '0';
  624. $power = '1';
  625. for ($i = \strlen($bytes) - 1; $i >= 0; $i--) {
  626. $index = \ord($bytes[$i]);
  627. if ($index !== 0) {
  628. $result = $this->add($result, ($index === 1)
  629. ? $power
  630. : $this->mul($power, (string) $index)
  631. );
  632. }
  633. if ($i !== 0) {
  634. $power = $this->mul($power, '256');
  635. }
  636. }
  637. return $result;
  638. }
  639. }