Calculator.php 19 KB

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