PageRenderTime 73ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/phpseclib/phpseclib/phpseclib/Math/BigInteger.php

https://bitbucket.org/Kamor/nexway
PHP | 3751 lines | 1985 code | 490 blank | 1276 comment | 401 complexity | 85986d3108c18ea28b434e4d0beda385 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause

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

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

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