PageRenderTime 70ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/vendors/phpseclib/Math/BigInteger.php

https://bitbucket.org/ttalov/fgcu_pci
PHP | 3553 lines | 1866 code | 466 blank | 1221 comment | 372 complexity | 4610d3112dc05e980489c7dbc5dae4b3 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Pure-PHP arbitrary precision integer arithmetic library.
  5. *
  6. * Supports base-2, base-10, base-16, and base-256 numbers. Uses the GMP or BCMath extensions, if available,
  7. * and an internal implementation, otherwise.
  8. *
  9. * PHP versions 4 and 5
  10. *
  11. * {@internal (all DocBlock comments regarding implementation - such as the one that follows - refer to the
  12. * {@link MATH_BIGINTEGER_MODE_INTERNAL MATH_BIGINTEGER_MODE_INTERNAL} mode)
  13. *
  14. * Math_BigInteger uses base-2**26 to perform operations such as multiplication and division and
  15. * base-2**52 (ie. two base 2**26 digits) to perform addition and subtraction. Because the largest possible
  16. * value when multiplying two base-2**26 numbers together is a base-2**52 number, double precision floating
  17. * point numbers - numbers that should be supported on most hardware and whose significand is 53 bits - are
  18. * used. As a consequence, bitwise operators such as >> and << cannot be used, nor can the modulo operator %,
  19. * which only supports integers. Although this fact will slow this library down, the fact that such a high
  20. * base is being used should more than compensate.
  21. *
  22. * When PHP version 6 is officially released, we'll be able to use 64-bit integers. This should, once again,
  23. * allow bitwise operators, and will increase the maximum possible base to 2**31 (or 2**62 for addition /
  24. * subtraction).
  25. *
  26. * Numbers are stored in {@link http://en.wikipedia.org/wiki/Endianness little endian} format. ie.
  27. * (new Math_BigInteger(pow(2, 26)))->value = array(0, 1)
  28. *
  29. * Useful resources are as follows:
  30. *
  31. * - {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf Handbook of Applied Cryptography (HAC)}
  32. * - {@link http://math.libtomcrypt.com/files/tommath.pdf Multi-Precision Math (MPM)}
  33. * - Java's BigInteger classes. See /j2se/src/share/classes/java/math in jdk-1_5_0-src-jrl.zip
  34. *
  35. * Here's an example of how to use this library:
  36. * <code>
  37. * <?php
  38. * include('Math/BigInteger.php');
  39. *
  40. * $a = new Math_BigInteger(2);
  41. * $b = new Math_BigInteger(3);
  42. *
  43. * $c = $a->add($b);
  44. *
  45. * echo $c->toString(); // outputs 5
  46. * ?>
  47. * </code>
  48. *
  49. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  50. * of this software and associated documentation files (the "Software"), to deal
  51. * in the Software without restriction, including without limitation the rights
  52. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  53. * copies of the Software, and to permit persons to whom the Software is
  54. * furnished to do so, subject to the following conditions:
  55. *
  56. * The above copyright notice and this permission notice shall be included in
  57. * all copies or substantial portions of the Software.
  58. *
  59. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  60. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  61. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  62. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  63. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  64. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  65. * THE SOFTWARE.
  66. *
  67. * @category Math
  68. * @package Math_BigInteger
  69. * @author Jim Wigginton <terrafrost@php.net>
  70. * @copyright MMVI Jim Wigginton
  71. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  72. * @version $Id: BigInteger.php 326530 2012-07-07 22:05:25Z terrafrost $
  73. * @link http://pear.php.net/package/Math_BigInteger
  74. */
  75. /**#@+
  76. * Reduction constants
  77. *
  78. * @access private
  79. * @see Math_BigInteger::_reduce()
  80. */
  81. /**
  82. * @see Math_BigInteger::_montgomery()
  83. * @see Math_BigInteger::_prepMontgomery()
  84. */
  85. define('MATH_BIGINTEGER_MONTGOMERY', 0);
  86. /**
  87. * @see Math_BigInteger::_barrett()
  88. */
  89. define('MATH_BIGINTEGER_BARRETT', 1);
  90. /**
  91. * @see Math_BigInteger::_mod2()
  92. */
  93. define('MATH_BIGINTEGER_POWEROF2', 2);
  94. /**
  95. * @see Math_BigInteger::_remainder()
  96. */
  97. define('MATH_BIGINTEGER_CLASSIC', 3);
  98. /**
  99. * @see Math_BigInteger::__clone()
  100. */
  101. define('MATH_BIGINTEGER_NONE', 4);
  102. /**#@-*/
  103. /**#@+
  104. * Array constants
  105. *
  106. * Rather than create a thousands and thousands of new Math_BigInteger objects in repeated function calls to add() and
  107. * multiply() or whatever, we'll just work directly on arrays, taking them in as parameters and returning them.
  108. *
  109. * @access private
  110. */
  111. /**
  112. * $result[MATH_BIGINTEGER_VALUE] contains the value.
  113. */
  114. define('MATH_BIGINTEGER_VALUE', 0);
  115. /**
  116. * $result[MATH_BIGINTEGER_SIGN] contains the sign.
  117. */
  118. define('MATH_BIGINTEGER_SIGN', 1);
  119. /**#@-*/
  120. /**#@+
  121. * @access private
  122. * @see Math_BigInteger::_montgomery()
  123. * @see Math_BigInteger::_barrett()
  124. */
  125. /**
  126. * Cache constants
  127. *
  128. * $cache[MATH_BIGINTEGER_VARIABLE] tells us whether or not the cached data is still valid.
  129. */
  130. define('MATH_BIGINTEGER_VARIABLE', 0);
  131. /**
  132. * $cache[MATH_BIGINTEGER_DATA] contains the cached data.
  133. */
  134. define('MATH_BIGINTEGER_DATA', 1);
  135. /**#@-*/
  136. /**#@+
  137. * Mode constants.
  138. *
  139. * @access private
  140. * @see Math_BigInteger::Math_BigInteger()
  141. */
  142. /**
  143. * To use the pure-PHP implementation
  144. */
  145. define('MATH_BIGINTEGER_MODE_INTERNAL', 1);
  146. /**
  147. * To use the BCMath library
  148. *
  149. * (if enabled; otherwise, the internal implementation will be used)
  150. */
  151. define('MATH_BIGINTEGER_MODE_BCMATH', 2);
  152. /**
  153. * To use the GMP library
  154. *
  155. * (if present; otherwise, either the BCMath or the internal implementation will be used)
  156. */
  157. define('MATH_BIGINTEGER_MODE_GMP', 3);
  158. /**#@-*/
  159. /**
  160. * The largest digit that may be used in addition / subtraction
  161. *
  162. * (we do pow(2, 52) instead of using 4503599627370496, directly, because some PHP installations
  163. * will truncate 4503599627370496)
  164. *
  165. * @access private
  166. */
  167. define('MATH_BIGINTEGER_MAX_DIGIT52', pow(2, 52));
  168. /**
  169. * Karatsuba Cutoff
  170. *
  171. * At what point do we switch between Karatsuba multiplication and schoolbook long multiplication?
  172. *
  173. * @access private
  174. */
  175. define('MATH_BIGINTEGER_KARATSUBA_CUTOFF', 25);
  176. /**
  177. * Pure-PHP arbitrary precision integer arithmetic library. Supports base-2, base-10, base-16, and base-256
  178. * numbers.
  179. *
  180. * @author Jim Wigginton <terrafrost@php.net>
  181. * @version 1.0.0RC4
  182. * @access public
  183. * @package Math_BigInteger
  184. */
  185. class Math_BigInteger {
  186. /**
  187. * Holds the BigInteger's value.
  188. *
  189. * @var Array
  190. * @access private
  191. */
  192. var $value;
  193. /**
  194. * Holds the BigInteger's magnitude.
  195. *
  196. * @var Boolean
  197. * @access private
  198. */
  199. var $is_negative = false;
  200. /**
  201. * Random number generator function
  202. *
  203. * @see setRandomGenerator()
  204. * @access private
  205. */
  206. var $generator = 'mt_rand';
  207. /**
  208. * Precision
  209. *
  210. * @see setPrecision()
  211. * @access private
  212. */
  213. var $precision = -1;
  214. /**
  215. * Precision Bitmask
  216. *
  217. * @see setPrecision()
  218. * @access private
  219. */
  220. var $bitmask = false;
  221. /**
  222. * Mode independant value used for serialization.
  223. *
  224. * If the bcmath or gmp extensions are installed $this->value will be a non-serializable resource, hence the need for
  225. * a variable that'll be serializable regardless of whether or not extensions are being used. Unlike $this->value,
  226. * however, $this->hex is only calculated when $this->__sleep() is called.
  227. *
  228. * @see __sleep()
  229. * @see __wakeup()
  230. * @var String
  231. * @access private
  232. */
  233. var $hex;
  234. /**
  235. * Converts base-2, base-10, base-16, and binary strings (eg. base-256) to BigIntegers.
  236. *
  237. * If the second parameter - $base - is negative, then it will be assumed that the number's are encoded using
  238. * two's compliment. The sole exception to this is -10, which is treated the same as 10 is.
  239. *
  240. * Here's an example:
  241. * <code>
  242. * <?php
  243. * include('Math/BigInteger.php');
  244. *
  245. * $a = new Math_BigInteger('0x32', 16); // 50 in base-16
  246. *
  247. * echo $a->toString(); // outputs 50
  248. * ?>
  249. * </code>
  250. *
  251. * @param optional $x base-10 number or base-$base number if $base set.
  252. * @param optional integer $base
  253. * @return Math_BigInteger
  254. * @access public
  255. */
  256. function Math_BigInteger($x = 0, $base = 10)
  257. {
  258. if ( !defined('MATH_BIGINTEGER_MODE') ) {
  259. switch (true) {
  260. case extension_loaded('gmp'):
  261. define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_GMP);
  262. break;
  263. case extension_loaded('bcmath'):
  264. define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_BCMATH);
  265. break;
  266. default:
  267. define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_INTERNAL);
  268. }
  269. }
  270. switch ( MATH_BIGINTEGER_MODE ) {
  271. case MATH_BIGINTEGER_MODE_GMP:
  272. if (is_resource($x) && get_resource_type($x) == 'GMP integer') {
  273. $this->value = $x;
  274. return;
  275. }
  276. $this->value = gmp_init(0);
  277. break;
  278. case MATH_BIGINTEGER_MODE_BCMATH:
  279. $this->value = '0';
  280. break;
  281. default:
  282. $this->value = array();
  283. }
  284. // '0' counts as empty() but when the base is 256 '0' is equal to ord('0') or 48
  285. // '0' is the only value like this per http://php.net/empty
  286. if (empty($x) && (abs($base) != 256 || $x !== '0')) {
  287. return;
  288. }
  289. switch ($base) {
  290. case -256:
  291. if (ord($x[0]) & 0x80) {
  292. $x = ~$x;
  293. $this->is_negative = true;
  294. }
  295. case 256:
  296. switch ( MATH_BIGINTEGER_MODE ) {
  297. case MATH_BIGINTEGER_MODE_GMP:
  298. $sign = $this->is_negative ? '-' : '';
  299. $this->value = gmp_init($sign . '0x' . bin2hex($x));
  300. break;
  301. case MATH_BIGINTEGER_MODE_BCMATH:
  302. // round $len to the nearest 4 (thanks, DavidMJ!)
  303. $len = (strlen($x) + 3) & 0xFFFFFFFC;
  304. $x = str_pad($x, $len, chr(0), STR_PAD_LEFT);
  305. for ($i = 0; $i < $len; $i+= 4) {
  306. $this->value = bcmul($this->value, '4294967296', 0); // 4294967296 == 2**32
  307. $this->value = bcadd($this->value, 0x1000000 * ord($x[$i]) + ((ord($x[$i + 1]) << 16) | (ord($x[$i + 2]) << 8) | ord($x[$i + 3])), 0);
  308. }
  309. if ($this->is_negative) {
  310. $this->value = '-' . $this->value;
  311. }
  312. break;
  313. // converts a base-2**8 (big endian / msb) number to base-2**26 (little endian / lsb)
  314. default:
  315. while (strlen($x)) {
  316. $this->value[] = $this->_bytes2int($this->_base256_rshift($x, 26));
  317. }
  318. }
  319. if ($this->is_negative) {
  320. if (MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_INTERNAL) {
  321. $this->is_negative = false;
  322. }
  323. $temp = $this->add(new Math_BigInteger('-1'));
  324. $this->value = $temp->value;
  325. }
  326. break;
  327. case 16:
  328. case -16:
  329. if ($base > 0 && $x[0] == '-') {
  330. $this->is_negative = true;
  331. $x = substr($x, 1);
  332. }
  333. $x = preg_replace('#^(?:0x)?([A-Fa-f0-9]*).*#', '$1', $x);
  334. $is_negative = false;
  335. if ($base < 0 && hexdec($x[0]) >= 8) {
  336. $this->is_negative = $is_negative = true;
  337. $x = bin2hex(~pack('H*', $x));
  338. }
  339. switch ( MATH_BIGINTEGER_MODE ) {
  340. case MATH_BIGINTEGER_MODE_GMP:
  341. $temp = $this->is_negative ? '-0x' . $x : '0x' . $x;
  342. $this->value = gmp_init($temp);
  343. $this->is_negative = false;
  344. break;
  345. case MATH_BIGINTEGER_MODE_BCMATH:
  346. $x = ( strlen($x) & 1 ) ? '0' . $x : $x;
  347. $temp = new Math_BigInteger(pack('H*', $x), 256);
  348. $this->value = $this->is_negative ? '-' . $temp->value : $temp->value;
  349. $this->is_negative = false;
  350. break;
  351. default:
  352. $x = ( strlen($x) & 1 ) ? '0' . $x : $x;
  353. $temp = new Math_BigInteger(pack('H*', $x), 256);
  354. $this->value = $temp->value;
  355. }
  356. if ($is_negative) {
  357. $temp = $this->add(new Math_BigInteger('-1'));
  358. $this->value = $temp->value;
  359. }
  360. break;
  361. case 10:
  362. case -10:
  363. $x = preg_replace('#^(-?[0-9]*).*#', '$1', $x);
  364. switch ( MATH_BIGINTEGER_MODE ) {
  365. case MATH_BIGINTEGER_MODE_GMP:
  366. $this->value = gmp_init($x);
  367. break;
  368. case MATH_BIGINTEGER_MODE_BCMATH:
  369. // explicitly casting $x to a string is necessary, here, since doing $x[0] on -1 yields different
  370. // results then doing it on '-1' does (modInverse does $x[0])
  371. $this->value = (string) $x;
  372. break;
  373. default:
  374. $temp = new Math_BigInteger();
  375. // array(10000000) is 10**7 in base-2**26. 10**7 is the closest to 2**26 we can get without passing it.
  376. $multiplier = new Math_BigInteger();
  377. $multiplier->value = array(10000000);
  378. if ($x[0] == '-') {
  379. $this->is_negative = true;
  380. $x = substr($x, 1);
  381. }
  382. $x = str_pad($x, strlen($x) + (6 * strlen($x)) % 7, 0, STR_PAD_LEFT);
  383. while (strlen($x)) {
  384. $temp = $temp->multiply($multiplier);
  385. $temp = $temp->add(new Math_BigInteger($this->_int2bytes(substr($x, 0, 7)), 256));
  386. $x = substr($x, 7);
  387. }
  388. $this->value = $temp->value;
  389. }
  390. break;
  391. case 2: // base-2 support originally implemented by Lluis Pamies - thanks!
  392. case -2:
  393. if ($base > 0 && $x[0] == '-') {
  394. $this->is_negative = true;
  395. $x = substr($x, 1);
  396. }
  397. $x = preg_replace('#^([01]*).*#', '$1', $x);
  398. $x = str_pad($x, strlen($x) + (3 * strlen($x)) % 4, 0, STR_PAD_LEFT);
  399. $str = '0x';
  400. while (strlen($x)) {
  401. $part = substr($x, 0, 4);
  402. $str.= dechex(bindec($part));
  403. $x = substr($x, 4);
  404. }
  405. if ($this->is_negative) {
  406. $str = '-' . $str;
  407. }
  408. $temp = new Math_BigInteger($str, 8 * $base); // ie. either -16 or +16
  409. $this->value = $temp->value;
  410. $this->is_negative = $temp->is_negative;
  411. break;
  412. default:
  413. // base not supported, so we'll let $this == 0
  414. }
  415. }
  416. /**
  417. * Converts a BigInteger to a byte string (eg. base-256).
  418. *
  419. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  420. * saved as two's compliment.
  421. *
  422. * Here's an example:
  423. * <code>
  424. * <?php
  425. * include('Math/BigInteger.php');
  426. *
  427. * $a = new Math_BigInteger('65');
  428. *
  429. * echo $a->toBytes(); // outputs chr(65)
  430. * ?>
  431. * </code>
  432. *
  433. * @param Boolean $twos_compliment
  434. * @return String
  435. * @access public
  436. * @internal Converts a base-2**26 number to base-2**8
  437. */
  438. function toBytes($twos_compliment = false)
  439. {
  440. if ($twos_compliment) {
  441. $comparison = $this->compare(new Math_BigInteger());
  442. if ($comparison == 0) {
  443. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  444. }
  445. $temp = $comparison < 0 ? $this->add(new Math_BigInteger(1)) : $this->copy();
  446. $bytes = $temp->toBytes();
  447. if (empty($bytes)) { // eg. if the number we're trying to convert is -1
  448. $bytes = chr(0);
  449. }
  450. if (ord($bytes[0]) & 0x80) {
  451. $bytes = chr(0) . $bytes;
  452. }
  453. return $comparison < 0 ? ~$bytes : $bytes;
  454. }
  455. switch ( MATH_BIGINTEGER_MODE ) {
  456. case MATH_BIGINTEGER_MODE_GMP:
  457. if (gmp_cmp($this->value, gmp_init(0)) == 0) {
  458. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  459. }
  460. $temp = gmp_strval(gmp_abs($this->value), 16);
  461. $temp = ( strlen($temp) & 1 ) ? '0' . $temp : $temp;
  462. $temp = pack('H*', $temp);
  463. return $this->precision > 0 ?
  464. substr(str_pad($temp, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  465. ltrim($temp, chr(0));
  466. case MATH_BIGINTEGER_MODE_BCMATH:
  467. if ($this->value === '0') {
  468. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  469. }
  470. $value = '';
  471. $current = $this->value;
  472. if ($current[0] == '-') {
  473. $current = substr($current, 1);
  474. }
  475. while (bccomp($current, '0', 0) > 0) {
  476. $temp = bcmod($current, '16777216');
  477. $value = chr($temp >> 16) . chr($temp >> 8) . chr($temp) . $value;
  478. $current = bcdiv($current, '16777216', 0);
  479. }
  480. return $this->precision > 0 ?
  481. substr(str_pad($value, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  482. ltrim($value, chr(0));
  483. }
  484. if (!count($this->value)) {
  485. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  486. }
  487. $result = $this->_int2bytes($this->value[count($this->value) - 1]);
  488. $temp = $this->copy();
  489. for ($i = count($temp->value) - 2; $i >= 0; --$i) {
  490. $temp->_base256_lshift($result, 26);
  491. $result = $result | str_pad($temp->_int2bytes($temp->value[$i]), strlen($result), chr(0), STR_PAD_LEFT);
  492. }
  493. return $this->precision > 0 ?
  494. str_pad(substr($result, -(($this->precision + 7) >> 3)), ($this->precision + 7) >> 3, chr(0), STR_PAD_LEFT) :
  495. $result;
  496. }
  497. /**
  498. * Converts a BigInteger to a hex string (eg. base-16)).
  499. *
  500. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  501. * saved as two's compliment.
  502. *
  503. * Here's an example:
  504. * <code>
  505. * <?php
  506. * include('Math/BigInteger.php');
  507. *
  508. * $a = new Math_BigInteger('65');
  509. *
  510. * echo $a->toHex(); // outputs '41'
  511. * ?>
  512. * </code>
  513. *
  514. * @param Boolean $twos_compliment
  515. * @return String
  516. * @access public
  517. * @internal Converts a base-2**26 number to base-2**8
  518. */
  519. function toHex($twos_compliment = false)
  520. {
  521. return bin2hex($this->toBytes($twos_compliment));
  522. }
  523. /**
  524. * Converts a BigInteger to a bit string (eg. base-2).
  525. *
  526. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  527. * saved as two's compliment.
  528. *
  529. * Here's an example:
  530. * <code>
  531. * <?php
  532. * include('Math/BigInteger.php');
  533. *
  534. * $a = new Math_BigInteger('65');
  535. *
  536. * echo $a->toBits(); // outputs '1000001'
  537. * ?>
  538. * </code>
  539. *
  540. * @param Boolean $twos_compliment
  541. * @return String
  542. * @access public
  543. * @internal Converts a base-2**26 number to base-2**2
  544. */
  545. function toBits($twos_compliment = false)
  546. {
  547. $hex = $this->toHex($twos_compliment);
  548. $bits = '';
  549. for ($i = 0, $end = strlen($hex) & 0xFFFFFFF8; $i < $end; $i+=8) {
  550. $bits.= str_pad(decbin(hexdec(substr($hex, $i, 8))), 32, '0', STR_PAD_LEFT);
  551. }
  552. if ($end != strlen($hex)) { // hexdec('') == 0
  553. $bits.= str_pad(decbin(hexdec(substr($hex, $end))), strlen($hex) & 7, '0', STR_PAD_LEFT);
  554. }
  555. return $this->precision > 0 ? substr($bits, -$this->precision) : ltrim($bits, '0');
  556. }
  557. /**
  558. * Converts a BigInteger to a base-10 number.
  559. *
  560. * Here's an example:
  561. * <code>
  562. * <?php
  563. * include('Math/BigInteger.php');
  564. *
  565. * $a = new Math_BigInteger('50');
  566. *
  567. * echo $a->toString(); // outputs 50
  568. * ?>
  569. * </code>
  570. *
  571. * @return String
  572. * @access public
  573. * @internal Converts a base-2**26 number to base-10**7 (which is pretty much base-10)
  574. */
  575. function toString()
  576. {
  577. switch ( MATH_BIGINTEGER_MODE ) {
  578. case MATH_BIGINTEGER_MODE_GMP:
  579. return gmp_strval($this->value);
  580. case MATH_BIGINTEGER_MODE_BCMATH:
  581. if ($this->value === '0') {
  582. return '0';
  583. }
  584. return ltrim($this->value, '0');
  585. }
  586. if (!count($this->value)) {
  587. return '0';
  588. }
  589. $temp = $this->copy();
  590. $temp->is_negative = false;
  591. $divisor = new Math_BigInteger();
  592. $divisor->value = array(10000000); // eg. 10**7
  593. $result = '';
  594. while (count($temp->value)) {
  595. list($temp, $mod) = $temp->divide($divisor);
  596. $result = str_pad(isset($mod->value[0]) ? $mod->value[0] : '', 7, '0', STR_PAD_LEFT) . $result;
  597. }
  598. $result = ltrim($result, '0');
  599. if (empty($result)) {
  600. $result = '0';
  601. }
  602. if ($this->is_negative) {
  603. $result = '-' . $result;
  604. }
  605. return $result;
  606. }
  607. /**
  608. * Copy an object
  609. *
  610. * PHP5 passes objects by reference while PHP4 passes by value. As such, we need a function to guarantee
  611. * that all objects are passed by value, when appropriate. More information can be found here:
  612. *
  613. * {@link http://php.net/language.oop5.basic#51624}
  614. *
  615. * @access public
  616. * @see __clone()
  617. * @return Math_BigInteger
  618. */
  619. function copy()
  620. {
  621. $temp = new Math_BigInteger();
  622. $temp->value = $this->value;
  623. $temp->is_negative = $this->is_negative;
  624. $temp->generator = $this->generator;
  625. $temp->precision = $this->precision;
  626. $temp->bitmask = $this->bitmask;
  627. return $temp;
  628. }
  629. /**
  630. * __toString() magic method
  631. *
  632. * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call
  633. * toString().
  634. *
  635. * @access public
  636. * @internal Implemented per a suggestion by Techie-Michael - thanks!
  637. */
  638. function __toString()
  639. {
  640. return $this->toString();
  641. }
  642. /**
  643. * __clone() magic method
  644. *
  645. * Although you can call Math_BigInteger::__toString() directly in PHP5, you cannot call Math_BigInteger::__clone()
  646. * directly in PHP5. You can in PHP4 since it's not a magic method, but in PHP5, you have to call it by using the PHP5
  647. * only syntax of $y = clone $x. As such, if you're trying to write an application that works on both PHP4 and PHP5,
  648. * call Math_BigInteger::copy(), instead.
  649. *
  650. * @access public
  651. * @see copy()
  652. * @return Math_BigInteger
  653. */
  654. function __clone()
  655. {
  656. return $this->copy();
  657. }
  658. /**
  659. * __sleep() magic method
  660. *
  661. * Will be called, automatically, when serialize() is called on a Math_BigInteger object.
  662. *
  663. * @see __wakeup()
  664. * @access public
  665. */
  666. function __sleep()
  667. {
  668. $this->hex = $this->toHex(true);
  669. $vars = array('hex');
  670. if ($this->generator != 'mt_rand') {
  671. $vars[] = 'generator';
  672. }
  673. if ($this->precision > 0) {
  674. $vars[] = 'precision';
  675. }
  676. return $vars;
  677. }
  678. /**
  679. * __wakeup() magic method
  680. *
  681. * Will be called, automatically, when unserialize() is called on a Math_BigInteger object.
  682. *
  683. * @see __sleep()
  684. * @access public
  685. */
  686. function __wakeup()
  687. {
  688. $temp = new Math_BigInteger($this->hex, -16);
  689. $this->value = $temp->value;
  690. $this->is_negative = $temp->is_negative;
  691. $this->setRandomGenerator($this->generator);
  692. if ($this->precision > 0) {
  693. // recalculate $this->bitmask
  694. $this->setPrecision($this->precision);
  695. }
  696. }
  697. /**
  698. * Adds two BigIntegers.
  699. *
  700. * Here's an example:
  701. * <code>
  702. * <?php
  703. * include('Math/BigInteger.php');
  704. *
  705. * $a = new Math_BigInteger('10');
  706. * $b = new Math_BigInteger('20');
  707. *
  708. * $c = $a->add($b);
  709. *
  710. * echo $c->toString(); // outputs 30
  711. * ?>
  712. * </code>
  713. *
  714. * @param Math_BigInteger $y
  715. * @return Math_BigInteger
  716. * @access public
  717. * @internal Performs base-2**52 addition
  718. */
  719. function add($y)
  720. {
  721. switch ( MATH_BIGINTEGER_MODE ) {
  722. case MATH_BIGINTEGER_MODE_GMP:
  723. $temp = new Math_BigInteger();
  724. $temp->value = gmp_add($this->value, $y->value);
  725. return $this->_normalize($temp);
  726. case MATH_BIGINTEGER_MODE_BCMATH:
  727. $temp = new Math_BigInteger();
  728. $temp->value = bcadd($this->value, $y->value, 0);
  729. return $this->_normalize($temp);
  730. }
  731. $temp = $this->_add($this->value, $this->is_negative, $y->value, $y->is_negative);
  732. $result = new Math_BigInteger();
  733. $result->value = $temp[MATH_BIGINTEGER_VALUE];
  734. $result->is_negative = $temp[MATH_BIGINTEGER_SIGN];
  735. return $this->_normalize($result);
  736. }
  737. /**
  738. * Performs addition.
  739. *
  740. * @param Array $x_value
  741. * @param Boolean $x_negative
  742. * @param Array $y_value
  743. * @param Boolean $y_negative
  744. * @return Array
  745. * @access private
  746. */
  747. function _add($x_value, $x_negative, $y_value, $y_negative)
  748. {
  749. $x_size = count($x_value);
  750. $y_size = count($y_value);
  751. if ($x_size == 0) {
  752. return array(
  753. MATH_BIGINTEGER_VALUE => $y_value,
  754. MATH_BIGINTEGER_SIGN => $y_negative
  755. );
  756. } else if ($y_size == 0) {
  757. return array(
  758. MATH_BIGINTEGER_VALUE => $x_value,
  759. MATH_BIGINTEGER_SIGN => $x_negative
  760. );
  761. }
  762. // subtract, if appropriate
  763. if ( $x_negative != $y_negative ) {
  764. if ( $x_value == $y_value ) {
  765. return array(
  766. MATH_BIGINTEGER_VALUE => array(),
  767. MATH_BIGINTEGER_SIGN => false
  768. );
  769. }
  770. $temp = $this->_subtract($x_value, false, $y_value, false);
  771. $temp[MATH_BIGINTEGER_SIGN] = $this->_compare($x_value, false, $y_value, false) > 0 ?
  772. $x_negative : $y_negative;
  773. return $temp;
  774. }
  775. if ($x_size < $y_size) {
  776. $size = $x_size;
  777. $value = $y_value;
  778. } else {
  779. $size = $y_size;
  780. $value = $x_value;
  781. }
  782. $value[] = 0; // just in case the carry adds an extra digit
  783. $carry = 0;
  784. for ($i = 0, $j = 1; $j < $size; $i+=2, $j+=2) {
  785. $sum = $x_value[$j] * 0x4000000 + $x_value[$i] + $y_value[$j] * 0x4000000 + $y_value[$i] + $carry;
  786. $carry = $sum >= MATH_BIGINTEGER_MAX_DIGIT52; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
  787. $sum = $carry ? $sum - MATH_BIGINTEGER_MAX_DIGIT52 : $sum;
  788. $temp = (int) ($sum / 0x4000000);
  789. $value[$i] = (int) ($sum - 0x4000000 * $temp); // eg. a faster alternative to fmod($sum, 0x4000000)
  790. $value[$j] = $temp;
  791. }
  792. if ($j == $size) { // ie. if $y_size is odd
  793. $sum = $x_value[$i] + $y_value[$i] + $carry;
  794. $carry = $sum >= 0x4000000;
  795. $value[$i] = $carry ? $sum - 0x4000000 : $sum;
  796. ++$i; // ie. let $i = $j since we've just done $value[$i]
  797. }
  798. if ($carry) {
  799. for (; $value[$i] == 0x3FFFFFF; ++$i) {
  800. $value[$i] = 0;
  801. }
  802. ++$value[$i];
  803. }
  804. return array(
  805. MATH_BIGINTEGER_VALUE => $this->_trim($value),
  806. MATH_BIGINTEGER_SIGN => $x_negative
  807. );
  808. }
  809. /**
  810. * Subtracts two BigIntegers.
  811. *
  812. * Here's an example:
  813. * <code>
  814. * <?php
  815. * include('Math/BigInteger.php');
  816. *
  817. * $a = new Math_BigInteger('10');
  818. * $b = new Math_BigInteger('20');
  819. *
  820. * $c = $a->subtract($b);
  821. *
  822. * echo $c->toString(); // outputs -10
  823. * ?>
  824. * </code>
  825. *
  826. * @param Math_BigInteger $y
  827. * @return Math_BigInteger
  828. * @access public
  829. * @internal Performs base-2**52 subtraction
  830. */
  831. function subtract($y)
  832. {
  833. switch ( MATH_BIGINTEGER_MODE ) {
  834. case MATH_BIGINTEGER_MODE_GMP:
  835. $temp = new Math_BigInteger();
  836. $temp->value = gmp_sub($this->value, $y->value);
  837. return $this->_normalize($temp);
  838. case MATH_BIGINTEGER_MODE_BCMATH:
  839. $temp = new Math_BigInteger();
  840. $temp->value = bcsub($this->value, $y->value, 0);
  841. return $this->_normalize($temp);
  842. }
  843. $temp = $this->_subtract($this->value, $this->is_negative, $y->value, $y->is_negative);
  844. $result = new Math_BigInteger();
  845. $result->value = $temp[MATH_BIGINTEGER_VALUE];
  846. $result->is_negative = $temp[MATH_BIGINTEGER_SIGN];
  847. return $this->_normalize($result);
  848. }
  849. /**
  850. * Performs subtraction.
  851. *
  852. * @param Array $x_value
  853. * @param Boolean $x_negative
  854. * @param Array $y_value
  855. * @param Boolean $y_negative
  856. * @return Array
  857. * @access private
  858. */
  859. function _subtract($x_value, $x_negative, $y_value, $y_negative)
  860. {
  861. $x_size = count($x_value);
  862. $y_size = count($y_value);
  863. if ($x_size == 0) {
  864. return array(
  865. MATH_BIGINTEGER_VALUE => $y_value,
  866. MATH_BIGINTEGER_SIGN => !$y_negative
  867. );
  868. } else if ($y_size == 0) {
  869. return array(
  870. MATH_BIGINTEGER_VALUE => $x_value,
  871. MATH_BIGINTEGER_SIGN => $x_negative
  872. );
  873. }
  874. // add, if appropriate (ie. -$x - +$y or +$x - -$y)
  875. if ( $x_negative != $y_negative ) {
  876. $temp = $this->_add($x_value, false, $y_value, false);
  877. $temp[MATH_BIGINTEGER_SIGN] = $x_negative;
  878. return $temp;
  879. }
  880. $diff = $this->_compare($x_value, $x_negative, $y_value, $y_negative);
  881. if ( !$diff ) {
  882. return array(
  883. MATH_BIGINTEGER_VALUE => array(),
  884. MATH_BIGINTEGER_SIGN => false
  885. );
  886. }
  887. // switch $x and $y around, if appropriate.
  888. if ( (!$x_negative && $diff < 0) || ($x_negative && $diff > 0) ) {
  889. $temp = $x_value;
  890. $x_value = $y_value;
  891. $y_value = $temp;
  892. $x_negative = !$x_negative;
  893. $x_size = count($x_value);
  894. $y_size = count($y_value);
  895. }
  896. // at this point, $x_value should be at least as big as - if not bigger than - $y_value
  897. $carry = 0;
  898. for ($i = 0, $j = 1; $j < $y_size; $i+=2, $j+=2) {
  899. $sum = $x_value[$j] * 0x4000000 + $x_value[$i] - $y_value[$j] * 0x4000000 - $y_value[$i] - $carry;
  900. $carry = $sum < 0; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
  901. $sum = $carry ? $sum + MATH_BIGINTEGER_MAX_DIGIT52 : $sum;
  902. $temp = (int) ($sum / 0x4000000);
  903. $x_value[$i] = (int) ($sum - 0x4000000 * $temp);
  904. $x_value[$j] = $temp;
  905. }
  906. if ($j == $y_size) { // ie. if $y_size is odd
  907. $sum = $x_value[$i] - $y_value[$i] - $carry;
  908. $carry = $sum < 0;
  909. $x_value[$i] = $carry ? $sum + 0x4000000 : $sum;
  910. ++$i;
  911. }
  912. if ($carry) {
  913. for (; !$x_value[$i]; ++$i) {
  914. $x_value[$i] = 0x3FFFFFF;
  915. }
  916. --$x_value[$i];
  917. }
  918. return array(
  919. MATH_BIGINTEGER_VALUE => $this->_trim($x_value),
  920. MATH_BIGINTEGER_SIGN => $x_negative
  921. );
  922. }
  923. /**
  924. * Multiplies two BigIntegers
  925. *
  926. * Here's an example:
  927. * <code>
  928. * <?php
  929. * include('Math/BigInteger.php');
  930. *
  931. * $a = new Math_BigInteger('10');
  932. * $b = new Math_BigInteger('20');
  933. *
  934. * $c = $a->multiply($b);
  935. *
  936. * echo $c->toString(); // outputs 200
  937. * ?>
  938. * </code>
  939. *
  940. * @param Math_BigInteger $x
  941. * @return Math_BigInteger
  942. * @access public
  943. */
  944. function multiply($x)
  945. {
  946. switch ( MATH_BIGINTEGER_MODE ) {
  947. case MATH_BIGINTEGER_MODE_GMP:
  948. $temp = new Math_BigInteger();
  949. $temp->value = gmp_mul($this->value, $x->value);
  950. return $this->_normalize($temp);
  951. case MATH_BIGINTEGER_MODE_BCMATH:
  952. $temp = new Math_BigInteger();
  953. $temp->value = bcmul($this->value, $x->value, 0);
  954. return $this->_normalize($temp);
  955. }
  956. $temp = $this->_multiply($this->value, $this->is_negative, $x->value, $x->is_negative);
  957. $product = new Math_BigInteger();
  958. $product->value = $temp[MATH_BIGINTEGER_VALUE];
  959. $product->is_negative = $temp[MATH_BIGINTEGER_SIGN];
  960. return $this->_normalize($product);
  961. }
  962. /**
  963. * Performs multiplication.
  964. *
  965. * @param Array $x_value
  966. * @param Boolean $x_negative
  967. * @param Array $y_value
  968. * @param Boolean $y_negative
  969. * @return Array
  970. * @access private
  971. */
  972. function _multiply($x_value, $x_negative, $y_value, $y_negative)
  973. {
  974. //if ( $x_value == $y_value ) {
  975. // return array(
  976. // MATH_BIGINTEGER_VALUE => $this->_square($x_value),
  977. // MATH_BIGINTEGER_SIGN => $x_sign != $y_value
  978. // );
  979. //}
  980. $x_length = count($x_value);
  981. $y_length = count($y_value);
  982. if ( !$x_length || !$y_length ) { // a 0 is being multiplied
  983. return array(
  984. MATH_BIGINTEGER_VALUE => array(),
  985. MATH_BIGINTEGER_SIGN => false
  986. );
  987. }
  988. return array(
  989. MATH_BIGINTEGER_VALUE => min($x_length, $y_length) < 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF ?
  990. $this->_trim($this->_regularMultiply($x_value, $y_value)) :
  991. $this->_trim($this->_karatsuba($x_value, $y_value)),
  992. MATH_BIGINTEGER_SIGN => $x_negative != $y_negative
  993. );
  994. }
  995. /**
  996. * Performs long multiplication on two BigIntegers
  997. *
  998. * Modeled after 'multiply' in MutableBigInteger.java.
  999. *
  1000. * @param Array $x_value
  1001. * @param Array $y_value
  1002. * @return Array
  1003. * @access private
  1004. */
  1005. function _regularMultiply($x_value, $y_value)
  1006. {
  1007. $x_length = count($x_value);
  1008. $y_length = count($y_value);
  1009. if ( !$x_length || !$y_length ) { // a 0 is being multiplied
  1010. return array();
  1011. }
  1012. if ( $x_length < $y_length ) {
  1013. $temp = $x_value;
  1014. $x_value = $y_value;
  1015. $y_value = $temp;
  1016. $x_length = count($x_value);
  1017. $y_length = count($y_value);
  1018. }
  1019. $product_value = $this->_array_repeat(0, $x_length + $y_length);
  1020. // the following for loop could be removed if the for loop following it
  1021. // (the one with nested for loops) initially set $i to 0, but
  1022. // doing so would also make the result in one set of unnecessary adds,
  1023. // since on the outermost loops first pass, $product->value[$k] is going
  1024. // to always be 0
  1025. $carry = 0;
  1026. for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0
  1027. $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0
  1028. $carry = (int) ($temp / 0x4000000);
  1029. $product_value[$j] = (int) ($temp - 0x4000000 * $carry);
  1030. }
  1031. $product_value[$j] = $carry;
  1032. // the above for loop is what the previous comment was talking about. the
  1033. // following for loop is the "one with nested for loops"
  1034. for ($i = 1; $i < $y_length; ++$i) {
  1035. $carry = 0;
  1036. for ($j = 0, $k = $i; $j < $x_length; ++$j, ++$k) {
  1037. $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry;
  1038. $carry = (int) ($temp / 0x4000000);
  1039. $product_value[$k] = (int) ($temp - 0x4000000 * $carry);
  1040. }
  1041. $product_value[$k] = $carry;
  1042. }
  1043. return $product_value;
  1044. }
  1045. /**
  1046. * Performs Karatsuba multiplication on two BigIntegers
  1047. *
  1048. * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
  1049. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=120 MPM 5.2.3}.
  1050. *
  1051. * @param Array $x_value
  1052. * @param Array $y_value
  1053. * @return Array
  1054. * @access private
  1055. */
  1056. function _karatsuba($x_value, $y_value)
  1057. {
  1058. $m = min(count($x_value) >> 1, count($y_value) >> 1);
  1059. if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) {
  1060. return $this->_regularMultiply($x_value, $y_value);
  1061. }
  1062. $x1 = array_slice($x_value, $m);
  1063. $x0 = array_slice($x_value, 0, $m);
  1064. $y1 = array_slice($y_value, $m);
  1065. $y0 = array_slice($y_value, 0, $m);
  1066. $z2 = $this->_karatsuba($x1, $y1);
  1067. $z0 = $this->_karatsuba($x0, $y0);
  1068. $z1 = $this->_add($x1, false, $x0, false);
  1069. $temp = $this->_add($y1, false, $y0, false);
  1070. $z1 = $this->_karatsuba($z1[MATH_BIGINTEGER_VALUE], $temp[MATH_BIGINTEGER_VALUE]);
  1071. $temp = $this->_add($z2, false, $z0, false);
  1072. $z1 = $this->_subtract($z1, false, $temp[MATH_BIGINTEGER_VALUE], false);
  1073. $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2);
  1074. $z1[MATH_BIGINTEGER_VALUE] = array_merge(array_fill(0, $m, 0), $z1[MATH_BIGINTEGER_VALUE]);
  1075. $xy = $this->_add($z2, false, $z1[MATH_BIGINTEGER_VALUE], $z1[MATH_BIGINTEGER_SIGN]);
  1076. $xy = $this->_add($xy[MATH_BIGINTEGER_VALUE], $xy[MATH_BIGINTEGER_SIGN], $z0, false);
  1077. return $xy[MATH_BIGINTEGER_VALUE];
  1078. }
  1079. /**
  1080. * Performs squaring
  1081. *
  1082. * @param Array $x
  1083. * @return Array
  1084. * @access private
  1085. */
  1086. function _square($x = false)
  1087. {
  1088. return count($x) < 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF ?
  1089. $this->_trim($this->_baseSquare($x)) :
  1090. $this->_trim($this->_karatsubaSquare($x));
  1091. }
  1092. /**
  1093. * Performs traditional squaring on two BigIntegers
  1094. *
  1095. * Squaring can be done faster than multiplying a number by itself can be. See
  1096. * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=7 HAC 14.2.4} /
  1097. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=141 MPM 5.3} for more information.
  1098. *
  1099. * @param Array $value
  1100. * @return Array
  1101. * @access private
  1102. */
  1103. function _baseSquare($value)
  1104. {
  1105. if ( empty($value) ) {
  1106. return array();
  1107. }
  1108. $square_value = $this->_array_repeat(0, 2 * count($value));
  1109. for ($i = 0, $max_index = count($value) - 1; $i <= $max_index; ++$i) {
  1110. $i2 = $i << 1;
  1111. $temp = $square_value[$i2] + $value[$i] * $value[$i];
  1112. $carry = (int) ($temp / 0x4000000);
  1113. $square_value[$i2] = (int) ($temp - 0x4000000 * $carry);
  1114. // note how we start from $i+1 instead of 0 as we do in multiplication.
  1115. for ($j = $i + 1, $k = $i2 + 1; $j <= $max_index; ++$j, ++$k) {
  1116. $temp = $square_value[$k] + 2 * $value[$j] * $value[$i] + $carry;
  1117. $carry = (int) ($temp / 0x4000000);
  1118. $square_value[$k] = (int) ($temp - 0x4000000 * $carry);
  1119. }
  1120. // the following line can yield values larger 2**15. at this point, PHP should switch
  1121. // over to floats.
  1122. $square_value[$i + $max_index + 1] = $carry;
  1123. }
  1124. return $square_value;
  1125. }
  1126. /**
  1127. * Performs Karatsuba "squaring" on two BigIntegers
  1128. *
  1129. * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
  1130. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=151 MPM 5.3.4}.
  1131. *
  1132. * @param Array $value
  1133. * @return Array
  1134. * @access private
  1135. */
  1136. function _karatsubaSquare($value)
  1137. {
  1138. $m = count($value) >> 1;
  1139. if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) {
  1140. return $this->_baseSquare($value);
  1141. }
  1142. $x1 = array_slice($value, $m);
  1143. $x0 = array_slice($value, 0, $m);
  1144. $z2 = $this->_karatsubaSquare($x1);
  1145. $z0 = $this->_karatsubaSquare($x0);
  1146. $z1 = $this->_add($x1, false, $x0, false);
  1147. $z1 = $this->_karatsubaSquare($z1[MATH_BIGINTEGER_VALUE]);
  1148. $temp = $this->_add($z2, false, $z0, false);
  1149. $z1 = $this->_subtract($z1, false, $temp[MATH_BIGINTEGER_VALUE], false);
  1150. $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2);
  1151. $z1[MATH_BIGINTEGER_VALUE] = array_merge(array_fill(0, $m, 0), $z1[MATH_BIGINTEGER_VALUE]);
  1152. $xx = $this->_add($z2, false, $z1[MATH_BIGINTEGER_VALUE], $z1[MATH_BIGINTEGER_SIGN]);
  1153. $xx = $this->_add($xx[MATH_BIGINTEGER_VALUE], $xx[MATH_BIGINTEGER_SIGN], $z0, false);
  1154. return $xx[MATH_BIGINTEGER_VALUE];
  1155. }
  1156. /**
  1157. * Divides two BigIntegers.
  1158. *
  1159. * Returns an array whose first element contains the quotient and whose second element contains the
  1160. * "common residue". If the remainder would be positive, the "common residue" and the remainder are the
  1161. * same. If the remainder would be negative, the "common residue" is equal to the sum of the remainder
  1162. * and the divisor (basically, the "common residue" is the first positive modulo).
  1163. *
  1164. * Here's an example:
  1165. * <code>
  1166. * <?php
  1167. * include('Math/BigInteger.php');
  1168. *
  1169. * $a = new Math_BigInteger('10');
  1170. * $b = new Math_BigInteger('20');
  1171. *
  1172. * list($quotient, $remainder) = $a->divide($b);
  1173. *
  1174. * echo $quotient->toString(); // outputs 0
  1175. * echo "\r\n";
  1176. * echo $remainder->toString(); // outputs 10
  1177. * ?>
  1178. * </code>
  1179. *
  1180. * @param Math_BigInteger $y
  1181. * @return Array
  1182. * @access public
  1183. * @internal This function is based off of {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=9 HAC 14.20}.
  1184. */
  1185. function divide($y)
  1186. {
  1187. switch ( MATH_BIGINTEGER_MODE ) {
  1188. case MATH_BIGINTEGER_MODE_GMP:
  1189. $quotient = new Math_BigInteger();
  1190. $remainder = new Math_BigInteger();
  1191. list($quotient->value, $remainder->value) = gmp_div_qr($this->value, $y->value);
  1192. if (gmp_sign($remainder->value) < 0) {
  1193. $remainder->value = gmp_add($remainder->value, gmp_abs($y->value));
  1194. }
  1195. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1196. case MATH_BIGINTEGER_MODE_BCMATH:
  1197. $quotient = new Math_BigInteger();
  1198. $remainder = new Math_BigInteger();
  1199. $quotient->value = bcdiv($this->value, $y->value, 0);
  1200. $remainder->value = bcmod($this->value, $y->value);
  1201. if ($remainder->value[0] == '-') {
  1202. $remainder->value = bcadd($remainder->value, $y->value[0] == '-' ? substr($y->value, 1) : $y->value, 0);
  1203. }
  1204. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1205. }
  1206. if (count($y->value) == 1) {
  1207. list($q, $r) = $this->_divide_digit($this->value, $y->value[0]);
  1208. $quotient = new Math_BigInteger();
  1209. $remainder = new Math_BigInteger();
  1210. $quotient->value = $q;
  1211. $remainder->value = array($r);
  1212. $quotient->is_negative = $this->is_negative != $y->is_negative;
  1213. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1214. }
  1215. static $zero;
  1216. if ( !isset($zero) ) {
  1217. $zero = new Math_BigInteger();
  1218. }
  1219. $x = $this->copy();
  1220. $y = $y->copy();
  1221. $x_sign = $x->is_negative;
  1222. $y_sign = $y->is_negative;
  1223. $x->is_negative = $y->is_negative = false;
  1224. $diff = $x->compare($y);
  1225. if ( !$diff ) {
  1226. $temp = new Math_BigInteger();
  1227. $temp->value = array(1);
  1228. $temp->is_negative = $x_sign != $y_sign;
  1229. return array($this->_normalize($temp), $this->_normalize(new Math_BigInteger()));
  1230. }
  1231. if ( $diff < 0 ) {
  1232. // if $x is negative, "add" $y.
  1233. if ( $x_sign ) {
  1234. $x = $y->subtract($x);
  1235. }
  1236. return array($this->_normalize(new Math_BigInteger()), $this->_normalize($x));
  1237. }
  1238. // normalize $x and $y as described in HAC 14.23 / 14.24
  1239. $msb = $y->value[count($y->value) - 1];
  1240. for ($shift = 0; !($msb & 0x2000000); ++$shift) {
  1241. $msb <<= 1;
  1242. }
  1243. $x->_lshift($shift);
  1244. $y->_lshift($shift);
  1245. $y_value = &$y->value;
  1246. $x_max = count($x->value) - 1;
  1247. $y_max = count($y->value) - 1;
  1248. $quotient = new Math_BigInteger();
  1249. $quotient_value = &$quotient->value;
  1250. $quotient_value = $this->_array_repeat(0, $x_max - $y_max + 1);
  1251. static $temp, $lhs, $rhs;
  1252. if (!isset($temp)) {
  1253. $temp = new Math_BigInteger();
  1254. $lhs = new Math_BigInteger();
  1255. $rhs = new Math_BigInteger();
  1256. }
  1257. $temp_value = &$temp->value;
  1258. $rhs_value = &$rhs->value;
  1259. // $temp = $y << ($x_max - $y_max-1) in base 2**26
  1260. $temp_value = array_merge($this->_array_repeat(0, $x_max - $y_max), $y_value);
  1261. while ( $x->compare($temp) >= 0 ) {
  1262. // calculate the "common residue"
  1263. ++$quotient_value[$x_max - $y_max];
  1264. $x = $x->subtract($temp);
  1265. $x_max = count($x->value) - 1;
  1266. }
  1267. for ($i = $x_max; $i >= $y_max + 1; --$i) {
  1268. $x_value = &$x->value;
  1269. $x_window = array(
  1270. isset($x_value[$i]) ? $x_value[$i] : 0,
  1271. isset($x_value[$i - 1]) ? $x_value[$i - 1] : 0,
  1272. isset($x_value[$i - 2]) ? $x_value[$i - 2] : 0
  1273. );
  1274. $y_window = array(
  1275. $y_value[$y_max],
  1276. ( $y_max > 0 ) ? $y_value[$y_max - 1] : 0
  1277. );
  1278. $q_index = $i - $y_max - 1;
  1279. if ($x_window[0] == $y_window[0]) {
  1280. $quotient_value[$q_index] = 0x3FFFFFF;
  1281. } else {
  1282. $quotient_value[$q_index] = (int) (
  1283. ($x_window[0] * 0x4000000 + $x_window[1])
  1284. /
  1285. $y_window[0]
  1286. );
  1287. }
  1288. $temp_value = array($y_window[1], $y_window[0]);
  1289. $lhs->value = array($quotient_value[$q_index]);
  1290. $lhs = $lhs->multiply($temp);
  1291. $rhs_value = array($x_window[2], $x_window[1], $x_window[0]);
  1292. while ( $lhs->compare($rhs) > 0 ) {
  1293. --$quotient_value[$q_index];
  1294. $lhs->value = array($quotient_value[$q_index]);
  1295. $lhs = $lhs->multiply($temp);
  1296. }
  1297. $adjust = $this->_array_repeat(0, $q_index);
  1298. $temp_value = array($quotient_value[$q_index]);
  1299. $temp = $temp->multiply($y);
  1300. $temp_value = &$temp->value;
  1301. $temp_value = array_merge($adjust, $temp_value);
  1302. $x = $x->subtract($temp);
  1303. if ($x->compare($zero) < 0) {
  1304. $temp_value = array_merge($adjust, $y_value);
  1305. $x = $x->add($temp);
  1306. --$quotient_value[$q_index];
  1307. }
  1308. $x_max = count($x_value) - 1;
  1309. }
  1310. // unnormalize the remainder
  1311. $x->_rshift($shift);
  1312. $quotient->is_negative = $x_sign != $y_sign;
  1313. // calculate the "common residue", if appropriate
  1314. if ( $x_sign ) {
  1315. $y->_rshift($shift);
  1316. $x = $y->subtract($x);
  1317. }
  1318. return array($this->_normalize($quotient), $this->_normalize($x));
  1319. }
  1320. /**
  1321. * Divides a BigInteger by a regular integer
  1322. *
  1323. * abc / x = a00 / x + b0 / x + c / x
  1324. *
  1325. * @param Array $dividend
  1326. * @param Array $divisor
  1327. * @return Array

Large files files are truncated, but you can click here to view the full file