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

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

https://bitbucket.org/devthiagolino/gepro-sistema
PHP | 3733 lines | 1976 code | 490 blank | 1267 comment | 399 complexity | cdb10de52eab7a9bf9ec10e651ce5002 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, CC-BY-3.0

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. if (is_resource($x) && get_resource_type($x) == 'GMP integer') {
  313. $this->value = $x;
  314. return;
  315. }
  316. $this->value = gmp_init(0);
  317. break;
  318. case MATH_BIGINTEGER_MODE_BCMATH:
  319. $this->value = '0';
  320. break;
  321. default:
  322. $this->value = array();
  323. }
  324. // '0' counts as empty() but when the base is 256 '0' is equal to ord('0') or 48
  325. // '0' is the only value like this per http://php.net/empty
  326. if (empty($x) && (abs($base) != 256 || $x !== '0')) {
  327. return;
  328. }
  329. switch ($base) {
  330. case -256:
  331. if (ord($x[0]) & 0x80) {
  332. $x = ~$x;
  333. $this->is_negative = true;
  334. }
  335. case 256:
  336. switch ( MATH_BIGINTEGER_MODE ) {
  337. case MATH_BIGINTEGER_MODE_GMP:
  338. $sign = $this->is_negative ? '-' : '';
  339. $this->value = gmp_init($sign . '0x' . bin2hex($x));
  340. break;
  341. case MATH_BIGINTEGER_MODE_BCMATH:
  342. // round $len to the nearest 4 (thanks, DavidMJ!)
  343. $len = (strlen($x) + 3) & 0xFFFFFFFC;
  344. $x = str_pad($x, $len, chr(0), STR_PAD_LEFT);
  345. for ($i = 0; $i < $len; $i+= 4) {
  346. $this->value = bcmul($this->value, '4294967296', 0); // 4294967296 == 2**32
  347. $this->value = bcadd($this->value, 0x1000000 * ord($x[$i]) + ((ord($x[$i + 1]) << 16) | (ord($x[$i + 2]) << 8) | ord($x[$i + 3])), 0);
  348. }
  349. if ($this->is_negative) {
  350. $this->value = '-' . $this->value;
  351. }
  352. break;
  353. // converts a base-2**8 (big endian / msb) number to base-2**26 (little endian / lsb)
  354. default:
  355. while (strlen($x)) {
  356. $this->value[] = $this->_bytes2int($this->_base256_rshift($x, MATH_BIGINTEGER_BASE));
  357. }
  358. }
  359. if ($this->is_negative) {
  360. if (MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_INTERNAL) {
  361. $this->is_negative = false;
  362. }
  363. $temp = $this->add(new Math_BigInteger('-1'));
  364. $this->value = $temp->value;
  365. }
  366. break;
  367. case 16:
  368. case -16:
  369. if ($base > 0 && $x[0] == '-') {
  370. $this->is_negative = true;
  371. $x = substr($x, 1);
  372. }
  373. $x = preg_replace('#^(?:0x)?([A-Fa-f0-9]*).*#', '$1', $x);
  374. $is_negative = false;
  375. if ($base < 0 && hexdec($x[0]) >= 8) {
  376. $this->is_negative = $is_negative = true;
  377. $x = bin2hex(~pack('H*', $x));
  378. }
  379. switch ( MATH_BIGINTEGER_MODE ) {
  380. case MATH_BIGINTEGER_MODE_GMP:
  381. $temp = $this->is_negative ? '-0x' . $x : '0x' . $x;
  382. $this->value = gmp_init($temp);
  383. $this->is_negative = false;
  384. break;
  385. case MATH_BIGINTEGER_MODE_BCMATH:
  386. $x = ( strlen($x) & 1 ) ? '0' . $x : $x;
  387. $temp = new Math_BigInteger(pack('H*', $x), 256);
  388. $this->value = $this->is_negative ? '-' . $temp->value : $temp->value;
  389. $this->is_negative = false;
  390. break;
  391. default:
  392. $x = ( strlen($x) & 1 ) ? '0' . $x : $x;
  393. $temp = new Math_BigInteger(pack('H*', $x), 256);
  394. $this->value = $temp->value;
  395. }
  396. if ($is_negative) {
  397. $temp = $this->add(new Math_BigInteger('-1'));
  398. $this->value = $temp->value;
  399. }
  400. break;
  401. case 10:
  402. case -10:
  403. // (?<!^)(?:-).*: find any -'s that aren't at the beginning and then any characters that follow that
  404. // (?<=^|-)0*: find any 0's that are preceded by the start of the string or by a - (ie. octals)
  405. // [^-0-9].*: find any non-numeric characters and then any characters that follow that
  406. $x = preg_replace('#(?<!^)(?:-).*|(?<=^|-)0*|[^-0-9].*#', '', $x);
  407. switch ( MATH_BIGINTEGER_MODE ) {
  408. case MATH_BIGINTEGER_MODE_GMP:
  409. $this->value = gmp_init($x);
  410. break;
  411. case MATH_BIGINTEGER_MODE_BCMATH:
  412. // explicitly casting $x to a string is necessary, here, since doing $x[0] on -1 yields different
  413. // results then doing it on '-1' does (modInverse does $x[0])
  414. $this->value = $x === '-' ? '0' : (string) $x;
  415. break;
  416. default:
  417. $temp = new Math_BigInteger();
  418. $multiplier = new Math_BigInteger();
  419. $multiplier->value = array(MATH_BIGINTEGER_MAX10);
  420. if ($x[0] == '-') {
  421. $this->is_negative = true;
  422. $x = substr($x, 1);
  423. }
  424. $x = str_pad($x, strlen($x) + ((MATH_BIGINTEGER_MAX10_LEN - 1) * strlen($x)) % MATH_BIGINTEGER_MAX10_LEN, 0, STR_PAD_LEFT);
  425. while (strlen($x)) {
  426. $temp = $temp->multiply($multiplier);
  427. $temp = $temp->add(new Math_BigInteger($this->_int2bytes(substr($x, 0, MATH_BIGINTEGER_MAX10_LEN)), 256));
  428. $x = substr($x, MATH_BIGINTEGER_MAX10_LEN);
  429. }
  430. $this->value = $temp->value;
  431. }
  432. break;
  433. case 2: // base-2 support originally implemented by Lluis Pamies - thanks!
  434. case -2:
  435. if ($base > 0 && $x[0] == '-') {
  436. $this->is_negative = true;
  437. $x = substr($x, 1);
  438. }
  439. $x = preg_replace('#^([01]*).*#', '$1', $x);
  440. $x = str_pad($x, strlen($x) + (3 * strlen($x)) % 4, 0, STR_PAD_LEFT);
  441. $str = '0x';
  442. while (strlen($x)) {
  443. $part = substr($x, 0, 4);
  444. $str.= dechex(bindec($part));
  445. $x = substr($x, 4);
  446. }
  447. if ($this->is_negative) {
  448. $str = '-' . $str;
  449. }
  450. $temp = new Math_BigInteger($str, 8 * $base); // ie. either -16 or +16
  451. $this->value = $temp->value;
  452. $this->is_negative = $temp->is_negative;
  453. break;
  454. default:
  455. // base not supported, so we'll let $this == 0
  456. }
  457. }
  458. /**
  459. * Converts a BigInteger to a byte string (eg. base-256).
  460. *
  461. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  462. * saved as two's compliment.
  463. *
  464. * Here's an example:
  465. * <code>
  466. * <?php
  467. * include('Math/BigInteger.php');
  468. *
  469. * $a = new Math_BigInteger('65');
  470. *
  471. * echo $a->toBytes(); // outputs chr(65)
  472. * ?>
  473. * </code>
  474. *
  475. * @param Boolean $twos_compliment
  476. * @return String
  477. * @access public
  478. * @internal Converts a base-2**26 number to base-2**8
  479. */
  480. function toBytes($twos_compliment = false)
  481. {
  482. if ($twos_compliment) {
  483. $comparison = $this->compare(new Math_BigInteger());
  484. if ($comparison == 0) {
  485. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  486. }
  487. $temp = $comparison < 0 ? $this->add(new Math_BigInteger(1)) : $this->copy();
  488. $bytes = $temp->toBytes();
  489. if (empty($bytes)) { // eg. if the number we're trying to convert is -1
  490. $bytes = chr(0);
  491. }
  492. if (ord($bytes[0]) & 0x80) {
  493. $bytes = chr(0) . $bytes;
  494. }
  495. return $comparison < 0 ? ~$bytes : $bytes;
  496. }
  497. switch ( MATH_BIGINTEGER_MODE ) {
  498. case MATH_BIGINTEGER_MODE_GMP:
  499. if (gmp_cmp($this->value, gmp_init(0)) == 0) {
  500. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  501. }
  502. $temp = gmp_strval(gmp_abs($this->value), 16);
  503. $temp = ( strlen($temp) & 1 ) ? '0' . $temp : $temp;
  504. $temp = pack('H*', $temp);
  505. return $this->precision > 0 ?
  506. substr(str_pad($temp, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  507. ltrim($temp, chr(0));
  508. case MATH_BIGINTEGER_MODE_BCMATH:
  509. if ($this->value === '0') {
  510. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  511. }
  512. $value = '';
  513. $current = $this->value;
  514. if ($current[0] == '-') {
  515. $current = substr($current, 1);
  516. }
  517. while (bccomp($current, '0', 0) > 0) {
  518. $temp = bcmod($current, '16777216');
  519. $value = chr($temp >> 16) . chr($temp >> 8) . chr($temp) . $value;
  520. $current = bcdiv($current, '16777216', 0);
  521. }
  522. return $this->precision > 0 ?
  523. substr(str_pad($value, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  524. ltrim($value, chr(0));
  525. }
  526. if (!count($this->value)) {
  527. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  528. }
  529. $result = $this->_int2bytes($this->value[count($this->value) - 1]);
  530. $temp = $this->copy();
  531. for ($i = count($temp->value) - 2; $i >= 0; --$i) {
  532. $temp->_base256_lshift($result, MATH_BIGINTEGER_BASE);
  533. $result = $result | str_pad($temp->_int2bytes($temp->value[$i]), strlen($result), chr(0), STR_PAD_LEFT);
  534. }
  535. return $this->precision > 0 ?
  536. str_pad(substr($result, -(($this->precision + 7) >> 3)), ($this->precision + 7) >> 3, chr(0), STR_PAD_LEFT) :
  537. $result;
  538. }
  539. /**
  540. * Converts a BigInteger to a hex string (eg. base-16)).
  541. *
  542. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  543. * saved as two's compliment.
  544. *
  545. * Here's an example:
  546. * <code>
  547. * <?php
  548. * include('Math/BigInteger.php');
  549. *
  550. * $a = new Math_BigInteger('65');
  551. *
  552. * echo $a->toHex(); // outputs '41'
  553. * ?>
  554. * </code>
  555. *
  556. * @param Boolean $twos_compliment
  557. * @return String
  558. * @access public
  559. * @internal Converts a base-2**26 number to base-2**8
  560. */
  561. function toHex($twos_compliment = false)
  562. {
  563. return bin2hex($this->toBytes($twos_compliment));
  564. }
  565. /**
  566. * Converts a BigInteger to a bit string (eg. base-2).
  567. *
  568. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  569. * saved as two's compliment.
  570. *
  571. * Here's an example:
  572. * <code>
  573. * <?php
  574. * include('Math/BigInteger.php');
  575. *
  576. * $a = new Math_BigInteger('65');
  577. *
  578. * echo $a->toBits(); // outputs '1000001'
  579. * ?>
  580. * </code>
  581. *
  582. * @param Boolean $twos_compliment
  583. * @return String
  584. * @access public
  585. * @internal Converts a base-2**26 number to base-2**2
  586. */
  587. function toBits($twos_compliment = false)
  588. {
  589. $hex = $this->toHex($twos_compliment);
  590. $bits = '';
  591. for ($i = strlen($hex) - 8, $start = strlen($hex) & 7; $i >= $start; $i-=8) {
  592. $bits = str_pad(decbin(hexdec(substr($hex, $i, 8))), 32, '0', STR_PAD_LEFT) . $bits;
  593. }
  594. if ($start) { // hexdec('') == 0
  595. $bits = str_pad(decbin(hexdec(substr($hex, 0, $start))), 8, '0', STR_PAD_LEFT) . $bits;
  596. }
  597. $result = $this->precision > 0 ? substr($bits, -$this->precision) : ltrim($bits, '0');
  598. if ($twos_compliment && $this->compare(new Math_BigInteger()) > 0 && $this->precision <= 0) {
  599. return '0' . $result;
  600. }
  601. return $result;
  602. }
  603. /**
  604. * Converts a BigInteger to a base-10 number.
  605. *
  606. * Here's an example:
  607. * <code>
  608. * <?php
  609. * include('Math/BigInteger.php');
  610. *
  611. * $a = new Math_BigInteger('50');
  612. *
  613. * echo $a->toString(); // outputs 50
  614. * ?>
  615. * </code>
  616. *
  617. * @return String
  618. * @access public
  619. * @internal Converts a base-2**26 number to base-10**7 (which is pretty much base-10)
  620. */
  621. function toString()
  622. {
  623. switch ( MATH_BIGINTEGER_MODE ) {
  624. case MATH_BIGINTEGER_MODE_GMP:
  625. return gmp_strval($this->value);
  626. case MATH_BIGINTEGER_MODE_BCMATH:
  627. if ($this->value === '0') {
  628. return '0';
  629. }
  630. return ltrim($this->value, '0');
  631. }
  632. if (!count($this->value)) {
  633. return '0';
  634. }
  635. $temp = $this->copy();
  636. $temp->is_negative = false;
  637. $divisor = new Math_BigInteger();
  638. $divisor->value = array(MATH_BIGINTEGER_MAX10);
  639. $result = '';
  640. while (count($temp->value)) {
  641. list($temp, $mod) = $temp->divide($divisor);
  642. $result = str_pad(isset($mod->value[0]) ? $mod->value[0] : '', MATH_BIGINTEGER_MAX10_LEN, '0', STR_PAD_LEFT) . $result;
  643. }
  644. $result = ltrim($result, '0');
  645. if (empty($result)) {
  646. $result = '0';
  647. }
  648. if ($this->is_negative) {
  649. $result = '-' . $result;
  650. }
  651. return $result;
  652. }
  653. /**
  654. * Copy an object
  655. *
  656. * PHP5 passes objects by reference while PHP4 passes by value. As such, we need a function to guarantee
  657. * that all objects are passed by value, when appropriate. More information can be found here:
  658. *
  659. * {@link http://php.net/language.oop5.basic#51624}
  660. *
  661. * @access public
  662. * @see __clone()
  663. * @return Math_BigInteger
  664. */
  665. function copy()
  666. {
  667. $temp = new Math_BigInteger();
  668. $temp->value = $this->value;
  669. $temp->is_negative = $this->is_negative;
  670. $temp->generator = $this->generator;
  671. $temp->precision = $this->precision;
  672. $temp->bitmask = $this->bitmask;
  673. return $temp;
  674. }
  675. /**
  676. * __toString() magic method
  677. *
  678. * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call
  679. * toString().
  680. *
  681. * @access public
  682. * @internal Implemented per a suggestion by Techie-Michael - thanks!
  683. */
  684. function __toString()
  685. {
  686. return $this->toString();
  687. }
  688. /**
  689. * __clone() magic method
  690. *
  691. * Although you can call Math_BigInteger::__toString() directly in PHP5, you cannot call Math_BigInteger::__clone()
  692. * 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
  693. * only syntax of $y = clone $x. As such, if you're trying to write an application that works on both PHP4 and PHP5,
  694. * call Math_BigInteger::copy(), instead.
  695. *
  696. * @access public
  697. * @see copy()
  698. * @return Math_BigInteger
  699. */
  700. function __clone()
  701. {
  702. return $this->copy();
  703. }
  704. /**
  705. * __sleep() magic method
  706. *
  707. * Will be called, automatically, when serialize() is called on a Math_BigInteger object.
  708. *
  709. * @see __wakeup()
  710. * @access public
  711. */
  712. function __sleep()
  713. {
  714. $this->hex = $this->toHex(true);
  715. $vars = array('hex');
  716. if ($this->generator != 'mt_rand') {
  717. $vars[] = 'generator';
  718. }
  719. if ($this->precision > 0) {
  720. $vars[] = 'precision';
  721. }
  722. return $vars;
  723. }
  724. /**
  725. * __wakeup() magic method
  726. *
  727. * Will be called, automatically, when unserialize() is called on a Math_BigInteger object.
  728. *
  729. * @see __sleep()
  730. * @access public
  731. */
  732. function __wakeup()
  733. {
  734. $temp = new Math_BigInteger($this->hex, -16);
  735. $this->value = $temp->value;
  736. $this->is_negative = $temp->is_negative;
  737. $this->setRandomGenerator($this->generator);
  738. if ($this->precision > 0) {
  739. // recalculate $this->bitmask
  740. $this->setPrecision($this->precision);
  741. }
  742. }
  743. /**
  744. * Adds two BigIntegers.
  745. *
  746. * Here's an example:
  747. * <code>
  748. * <?php
  749. * include('Math/BigInteger.php');
  750. *
  751. * $a = new Math_BigInteger('10');
  752. * $b = new Math_BigInteger('20');
  753. *
  754. * $c = $a->add($b);
  755. *
  756. * echo $c->toString(); // outputs 30
  757. * ?>
  758. * </code>
  759. *
  760. * @param Math_BigInteger $y
  761. * @return Math_BigInteger
  762. * @access public
  763. * @internal Performs base-2**52 addition
  764. */
  765. function add($y)
  766. {
  767. switch ( MATH_BIGINTEGER_MODE ) {
  768. case MATH_BIGINTEGER_MODE_GMP:
  769. $temp = new Math_BigInteger();
  770. $temp->value = gmp_add($this->value, $y->value);
  771. return $this->_normalize($temp);
  772. case MATH_BIGINTEGER_MODE_BCMATH:
  773. $temp = new Math_BigInteger();
  774. $temp->value = bcadd($this->value, $y->value, 0);
  775. return $this->_normalize($temp);
  776. }
  777. $temp = $this->_add($this->value, $this->is_negative, $y->value, $y->is_negative);
  778. $result = new Math_BigInteger();
  779. $result->value = $temp[MATH_BIGINTEGER_VALUE];
  780. $result->is_negative = $temp[MATH_BIGINTEGER_SIGN];
  781. return $this->_normalize($result);
  782. }
  783. /**
  784. * Performs addition.
  785. *
  786. * @param Array $x_value
  787. * @param Boolean $x_negative
  788. * @param Array $y_value
  789. * @param Boolean $y_negative
  790. * @return Array
  791. * @access private
  792. */
  793. function _add($x_value, $x_negative, $y_value, $y_negative)
  794. {
  795. $x_size = count($x_value);
  796. $y_size = count($y_value);
  797. if ($x_size == 0) {
  798. return array(
  799. MATH_BIGINTEGER_VALUE => $y_value,
  800. MATH_BIGINTEGER_SIGN => $y_negative
  801. );
  802. } else if ($y_size == 0) {
  803. return array(
  804. MATH_BIGINTEGER_VALUE => $x_value,
  805. MATH_BIGINTEGER_SIGN => $x_negative
  806. );
  807. }
  808. // subtract, if appropriate
  809. if ( $x_negative != $y_negative ) {
  810. if ( $x_value == $y_value ) {
  811. return array(
  812. MATH_BIGINTEGER_VALUE => array(),
  813. MATH_BIGINTEGER_SIGN => false
  814. );
  815. }
  816. $temp = $this->_subtract($x_value, false, $y_value, false);
  817. $temp[MATH_BIGINTEGER_SIGN] = $this->_compare($x_value, false, $y_value, false) > 0 ?
  818. $x_negative : $y_negative;
  819. return $temp;
  820. }
  821. if ($x_size < $y_size) {
  822. $size = $x_size;
  823. $value = $y_value;
  824. } else {
  825. $size = $y_size;
  826. $value = $x_value;
  827. }
  828. $value[] = 0; // just in case the carry adds an extra digit
  829. $carry = 0;
  830. for ($i = 0, $j = 1; $j < $size; $i+=2, $j+=2) {
  831. $sum = $x_value[$j] * MATH_BIGINTEGER_BASE_FULL + $x_value[$i] + $y_value[$j] * MATH_BIGINTEGER_BASE_FULL + $y_value[$i] + $carry;
  832. $carry = $sum >= MATH_BIGINTEGER_MAX_DIGIT2; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
  833. $sum = $carry ? $sum - MATH_BIGINTEGER_MAX_DIGIT2 : $sum;
  834. $temp = MATH_BIGINTEGER_BASE === 26 ? intval($sum / 0x4000000) : ($sum >> 31);
  835. $value[$i] = (int) ($sum - MATH_BIGINTEGER_BASE_FULL * $temp); // eg. a faster alternative to fmod($sum, 0x4000000)
  836. $value[$j] = $temp;
  837. }
  838. if ($j == $size) { // ie. if $y_size is odd
  839. $sum = $x_value[$i] + $y_value[$i] + $carry;
  840. $carry = $sum >= MATH_BIGINTEGER_BASE_FULL;
  841. $value[$i] = $carry ? $sum - MATH_BIGINTEGER_BASE_FULL : $sum;
  842. ++$i; // ie. let $i = $j since we've just done $value[$i]
  843. }
  844. if ($carry) {
  845. for (; $value[$i] == MATH_BIGINTEGER_MAX_DIGIT; ++$i) {
  846. $value[$i] = 0;
  847. }
  848. ++$value[$i];
  849. }
  850. return array(
  851. MATH_BIGINTEGER_VALUE => $this->_trim($value),
  852. MATH_BIGINTEGER_SIGN => $x_negative
  853. );
  854. }
  855. /**
  856. * Subtracts two BigIntegers.
  857. *
  858. * Here's an example:
  859. * <code>
  860. * <?php
  861. * include('Math/BigInteger.php');
  862. *
  863. * $a = new Math_BigInteger('10');
  864. * $b = new Math_BigInteger('20');
  865. *
  866. * $c = $a->subtract($b);
  867. *
  868. * echo $c->toString(); // outputs -10
  869. * ?>
  870. * </code>
  871. *
  872. * @param Math_BigInteger $y
  873. * @return Math_BigInteger
  874. * @access public
  875. * @internal Performs base-2**52 subtraction
  876. */
  877. function subtract($y)
  878. {
  879. switch ( MATH_BIGINTEGER_MODE ) {
  880. case MATH_BIGINTEGER_MODE_GMP:
  881. $temp = new Math_BigInteger();
  882. $temp->value = gmp_sub($this->value, $y->value);
  883. return $this->_normalize($temp);
  884. case MATH_BIGINTEGER_MODE_BCMATH:
  885. $temp = new Math_BigInteger();
  886. $temp->value = bcsub($this->value, $y->value, 0);
  887. return $this->_normalize($temp);
  888. }
  889. $temp = $this->_subtract($this->value, $this->is_negative, $y->value, $y->is_negative);
  890. $result = new Math_BigInteger();
  891. $result->value = $temp[MATH_BIGINTEGER_VALUE];
  892. $result->is_negative = $temp[MATH_BIGINTEGER_SIGN];
  893. return $this->_normalize($result);
  894. }
  895. /**
  896. * Performs subtraction.
  897. *
  898. * @param Array $x_value
  899. * @param Boolean $x_negative
  900. * @param Array $y_value
  901. * @param Boolean $y_negative
  902. * @return Array
  903. * @access private
  904. */
  905. function _subtract($x_value, $x_negative, $y_value, $y_negative)
  906. {
  907. $x_size = count($x_value);
  908. $y_size = count($y_value);
  909. if ($x_size == 0) {
  910. return array(
  911. MATH_BIGINTEGER_VALUE => $y_value,
  912. MATH_BIGINTEGER_SIGN => !$y_negative
  913. );
  914. } else if ($y_size == 0) {
  915. return array(
  916. MATH_BIGINTEGER_VALUE => $x_value,
  917. MATH_BIGINTEGER_SIGN => $x_negative
  918. );
  919. }
  920. // add, if appropriate (ie. -$x - +$y or +$x - -$y)
  921. if ( $x_negative != $y_negative ) {
  922. $temp = $this->_add($x_value, false, $y_value, false);
  923. $temp[MATH_BIGINTEGER_SIGN] = $x_negative;
  924. return $temp;
  925. }
  926. $diff = $this->_compare($x_value, $x_negative, $y_value, $y_negative);
  927. if ( !$diff ) {
  928. return array(
  929. MATH_BIGINTEGER_VALUE => array(),
  930. MATH_BIGINTEGER_SIGN => false
  931. );
  932. }
  933. // switch $x and $y around, if appropriate.
  934. if ( (!$x_negative && $diff < 0) || ($x_negative && $diff > 0) ) {
  935. $temp = $x_value;
  936. $x_value = $y_value;
  937. $y_value = $temp;
  938. $x_negative = !$x_negative;
  939. $x_size = count($x_value);
  940. $y_size = count($y_value);
  941. }
  942. // at this point, $x_value should be at least as big as - if not bigger than - $y_value
  943. $carry = 0;
  944. for ($i = 0, $j = 1; $j < $y_size; $i+=2, $j+=2) {
  945. $sum = $x_value[$j] * MATH_BIGINTEGER_BASE_FULL + $x_value[$i] - $y_value[$j] * MATH_BIGINTEGER_BASE_FULL - $y_value[$i] - $carry;
  946. $carry = $sum < 0; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
  947. $sum = $carry ? $sum + MATH_BIGINTEGER_MAX_DIGIT2 : $sum;
  948. $temp = MATH_BIGINTEGER_BASE === 26 ? intval($sum / 0x4000000) : ($sum >> 31);
  949. $x_value[$i] = (int) ($sum - MATH_BIGINTEGER_BASE_FULL * $temp);
  950. $x_value[$j] = $temp;
  951. }
  952. if ($j == $y_size) { // ie. if $y_size is odd
  953. $sum = $x_value[$i] - $y_value[$i] - $carry;
  954. $carry = $sum < 0;
  955. $x_value[$i] = $carry ? $sum + MATH_BIGINTEGER_BASE_FULL : $sum;
  956. ++$i;
  957. }
  958. if ($carry) {
  959. for (; !$x_value[$i]; ++$i) {
  960. $x_value[$i] = MATH_BIGINTEGER_MAX_DIGIT;
  961. }
  962. --$x_value[$i];
  963. }
  964. return array(
  965. MATH_BIGINTEGER_VALUE => $this->_trim($x_value),
  966. MATH_BIGINTEGER_SIGN => $x_negative
  967. );
  968. }
  969. /**
  970. * Multiplies two BigIntegers
  971. *
  972. * Here's an example:
  973. * <code>
  974. * <?php
  975. * include('Math/BigInteger.php');
  976. *
  977. * $a = new Math_BigInteger('10');
  978. * $b = new Math_BigInteger('20');
  979. *
  980. * $c = $a->multiply($b);
  981. *
  982. * echo $c->toString(); // outputs 200
  983. * ?>
  984. * </code>
  985. *
  986. * @param Math_BigInteger $x
  987. * @return Math_BigInteger
  988. * @access public
  989. */
  990. function multiply($x)
  991. {
  992. switch ( MATH_BIGINTEGER_MODE ) {
  993. case MATH_BIGINTEGER_MODE_GMP:
  994. $temp = new Math_BigInteger();
  995. $temp->value = gmp_mul($this->value, $x->value);
  996. return $this->_normalize($temp);
  997. case MATH_BIGINTEGER_MODE_BCMATH:
  998. $temp = new Math_BigInteger();
  999. $temp->value = bcmul($this->value, $x->value, 0);
  1000. return $this->_normalize($temp);
  1001. }
  1002. $temp = $this->_multiply($this->value, $this->is_negative, $x->value, $x->is_negative);
  1003. $product = new Math_BigInteger();
  1004. $product->value = $temp[MATH_BIGINTEGER_VALUE];
  1005. $product->is_negative = $temp[MATH_BIGINTEGER_SIGN];
  1006. return $this->_normalize($product);
  1007. }
  1008. /**
  1009. * Performs multiplication.
  1010. *
  1011. * @param Array $x_value
  1012. * @param Boolean $x_negative
  1013. * @param Array $y_value
  1014. * @param Boolean $y_negative
  1015. * @return Array
  1016. * @access private
  1017. */
  1018. function _multiply($x_value, $x_negative, $y_value, $y_negative)
  1019. {
  1020. //if ( $x_value == $y_value ) {
  1021. // return array(
  1022. // MATH_BIGINTEGER_VALUE => $this->_square($x_value),
  1023. // MATH_BIGINTEGER_SIGN => $x_sign != $y_value
  1024. // );
  1025. //}
  1026. $x_length = count($x_value);
  1027. $y_length = count($y_value);
  1028. if ( !$x_length || !$y_length ) { // a 0 is being multiplied
  1029. return array(
  1030. MATH_BIGINTEGER_VALUE => array(),
  1031. MATH_BIGINTEGER_SIGN => false
  1032. );
  1033. }
  1034. return array(
  1035. MATH_BIGINTEGER_VALUE => min($x_length, $y_length) < 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF ?
  1036. $this->_trim($this->_regularMultiply($x_value, $y_value)) :
  1037. $this->_trim($this->_karatsuba($x_value, $y_value)),
  1038. MATH_BIGINTEGER_SIGN => $x_negative != $y_negative
  1039. );
  1040. }
  1041. /**
  1042. * Performs long multiplication on two BigIntegers
  1043. *
  1044. * Modeled after 'multiply' in MutableBigInteger.java.
  1045. *
  1046. * @param Array $x_value
  1047. * @param Array $y_value
  1048. * @return Array
  1049. * @access private
  1050. */
  1051. function _regularMultiply($x_value, $y_value)
  1052. {
  1053. $x_length = count($x_value);
  1054. $y_length = count($y_value);
  1055. if ( !$x_length || !$y_length ) { // a 0 is being multiplied
  1056. return array();
  1057. }
  1058. if ( $x_length < $y_length ) {
  1059. $temp = $x_value;
  1060. $x_value = $y_value;
  1061. $y_value = $temp;
  1062. $x_length = count($x_value);
  1063. $y_length = count($y_value);
  1064. }
  1065. $product_value = $this->_array_repeat(0, $x_length + $y_length);
  1066. // the following for loop could be removed if the for loop following it
  1067. // (the one with nested for loops) initially set $i to 0, but
  1068. // doing so would also make the result in one set of unnecessary adds,
  1069. // since on the outermost loops first pass, $product->value[$k] is going
  1070. // to always be 0
  1071. $carry = 0;
  1072. for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0
  1073. $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0
  1074. $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1075. $product_value[$j] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
  1076. }
  1077. $product_value[$j] = $carry;
  1078. // the above for loop is what the previous comment was talking about. the
  1079. // following for loop is the "one with nested for loops"
  1080. for ($i = 1; $i < $y_length; ++$i) {
  1081. $carry = 0;
  1082. for ($j = 0, $k = $i; $j < $x_length; ++$j, ++$k) {
  1083. $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry;
  1084. $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1085. $product_value[$k] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
  1086. }
  1087. $product_value[$k] = $carry;
  1088. }
  1089. return $product_value;
  1090. }
  1091. /**
  1092. * Performs Karatsuba multiplication on two BigIntegers
  1093. *
  1094. * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
  1095. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=120 MPM 5.2.3}.
  1096. *
  1097. * @param Array $x_value
  1098. * @param Array $y_value
  1099. * @return Array
  1100. * @access private
  1101. */
  1102. function _karatsuba($x_value, $y_value)
  1103. {
  1104. $m = min(count($x_value) >> 1, count($y_value) >> 1);
  1105. if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) {
  1106. return $this->_regularMultiply($x_value, $y_value);
  1107. }
  1108. $x1 = array_slice($x_value, $m);
  1109. $x0 = array_slice($x_value, 0, $m);
  1110. $y1 = array_slice($y_value, $m);
  1111. $y0 = array_slice($y_value, 0, $m);
  1112. $z2 = $this->_karatsuba($x1, $y1);
  1113. $z0 = $this->_karatsuba($x0, $y0);
  1114. $z1 = $this->_add($x1, false, $x0, false);
  1115. $temp = $this->_add($y1, false, $y0, false);
  1116. $z1 = $this->_karatsuba($z1[MATH_BIGINTEGER_VALUE], $temp[MATH_BIGINTEGER_VALUE]);
  1117. $temp = $this->_add($z2, false, $z0, false);
  1118. $z1 = $this->_subtract($z1, false, $temp[MATH_BIGINTEGER_VALUE], false);
  1119. $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2);
  1120. $z1[MATH_BIGINTEGER_VALUE] = array_merge(array_fill(0, $m, 0), $z1[MATH_BIGINTEGER_VALUE]);
  1121. $xy = $this->_add($z2, false, $z1[MATH_BIGINTEGER_VALUE], $z1[MATH_BIGINTEGER_SIGN]);
  1122. $xy = $this->_add($xy[MATH_BIGINTEGER_VALUE], $xy[MATH_BIGINTEGER_SIGN], $z0, false);
  1123. return $xy[MATH_BIGINTEGER_VALUE];
  1124. }
  1125. /**
  1126. * Performs squaring
  1127. *
  1128. * @param Array $x
  1129. * @return Array
  1130. * @access private
  1131. */
  1132. function _square($x = false)
  1133. {
  1134. return count($x) < 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF ?
  1135. $this->_trim($this->_baseSquare($x)) :
  1136. $this->_trim($this->_karatsubaSquare($x));
  1137. }
  1138. /**
  1139. * Performs traditional squaring on two BigIntegers
  1140. *
  1141. * Squaring can be done faster than multiplying a number by itself can be. See
  1142. * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=7 HAC 14.2.4} /
  1143. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=141 MPM 5.3} for more information.
  1144. *
  1145. * @param Array $value
  1146. * @return Array
  1147. * @access private
  1148. */
  1149. function _baseSquare($value)
  1150. {
  1151. if ( empty($value) ) {
  1152. return array();
  1153. }
  1154. $square_value = $this->_array_repeat(0, 2 * count($value));
  1155. for ($i = 0, $max_index = count($value) - 1; $i <= $max_index; ++$i) {
  1156. $i2 = $i << 1;
  1157. $temp = $square_value[$i2] + $value[$i] * $value[$i];
  1158. $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1159. $square_value[$i2] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
  1160. // note how we start from $i+1 instead of 0 as we do in multiplication.
  1161. for ($j = $i + 1, $k = $i2 + 1; $j <= $max_index; ++$j, ++$k) {
  1162. $temp = $square_value[$k] + 2 * $value[$j] * $value[$i] + $carry;
  1163. $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
  1164. $square_value[$k] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry);
  1165. }
  1166. // the following line can yield values larger 2**15. at this point, PHP should switch
  1167. // over to floats.
  1168. $square_value[$i + $max_index + 1] = $carry;
  1169. }
  1170. return $square_value;
  1171. }
  1172. /**
  1173. * Performs Karatsuba "squaring" on two BigIntegers
  1174. *
  1175. * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
  1176. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=151 MPM 5.3.4}.
  1177. *
  1178. * @param Array $value
  1179. * @return Array
  1180. * @access private
  1181. */
  1182. function _karatsubaSquare($value)
  1183. {
  1184. $m = count($value) >> 1;
  1185. if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) {
  1186. return $this->_baseSquare($value);
  1187. }
  1188. $x1 = array_slice($value, $m);
  1189. $x0 = array_slice($value, 0, $m);
  1190. $z2 = $this->_karatsubaSquare($x1);
  1191. $z0 = $this->_karatsubaSquare($x0);
  1192. $z1 = $this->_add($x1, false, $x0, false);
  1193. $z1 = $this->_karatsubaSquare($z1[MATH_BIGINTEGER_VALUE]);
  1194. $temp = $this->_add($z2, false, $z0, false);
  1195. $z1 = $this->_subtract($z1, false, $temp[MATH_BIGINTEGER_VALUE], false);
  1196. $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2);
  1197. $z1[MATH_BIGINTEGER_VALUE] = array_merge(array_fill(0, $m, 0), $z1[MATH_BIGINTEGER_VALUE]);
  1198. $xx = $this->_add($z2, false, $z1[MATH_BIGINTEGER_VALUE], $z1[MATH_BIGINTEGER_SIGN]);
  1199. $xx = $this->_add($xx[MATH_BIGINTEGER_VALUE], $xx[MATH_BIGINTEGER_SIGN], $z0, false);
  1200. return $xx[MATH_BIGINTEGER_VALUE];
  1201. }
  1202. /**
  1203. * Divides two BigIntegers.
  1204. *
  1205. * Returns an array whose first element contains the quotient and whose second element contains the
  1206. * "common residue". If the remainder would be positive, the "common residue" and the remainder are the
  1207. * same. If the remainder would be negative, the "common residue" is equal to the sum of the remainder
  1208. * and the divisor (basically, the "common residue" is the first positive modulo).
  1209. *
  1210. * Here's an example:
  1211. * <code>
  1212. * <?php
  1213. * include('Math/BigInteger.php');
  1214. *
  1215. * $a = new Math_BigInteger('10');
  1216. * $b = new Math_BigInteger('20');
  1217. *
  1218. * list($quotient, $remainder) = $a->divide($b);
  1219. *
  1220. * echo $quotient->toString(); // outputs 0
  1221. * echo "\r\n";
  1222. * echo $remainder->toString(); // outputs 10
  1223. * ?>
  1224. * </code>
  1225. *
  1226. * @param Math_BigInteger $y
  1227. * @return Array
  1228. * @access public
  1229. * @internal This function is based off of {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=9 HAC 14.20}.
  1230. */
  1231. function divide($y)
  1232. {
  1233. switch ( MATH_BIGINTEGER_MODE ) {
  1234. case MATH_BIGINTEGER_MODE_GMP:
  1235. $quotient = new Math_BigInteger();
  1236. $remainder = new Math_BigInteger();
  1237. list($quotient->value, $remainder->value) = gmp_div_qr($this->value, $y->value);
  1238. if (gmp_sign($remainder->value) < 0) {
  1239. $remainder->value = gmp_add($remainder->value, gmp_abs($y->value));
  1240. }
  1241. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1242. case MATH_BIGINTEGER_MODE_BCMATH:
  1243. $quotient = new Math_BigInteger();
  1244. $remainder = new Math_BigInteger();
  1245. $quotient->value = bcdiv($this->value, $y->value, 0);
  1246. $remainder->value = bcmod($this->value, $y->value);
  1247. if ($remainder->value[0] == '-') {
  1248. $remainder->value = bcadd($remainder->value, $y->value[0] == '-' ? substr($y->value, 1) : $y->value, 0);
  1249. }
  1250. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1251. }
  1252. if (count($y->value) == 1) {
  1253. list($q, $r) = $this->_divide_digit($this->value, $y->value[0]);
  1254. $quotient = new Math_BigInteger();
  1255. $remainder = new Math_BigInteger();
  1256. $quotient->value = $q;
  1257. $remainder->value = array($r);
  1258. $quotient->is_negative = $this->is_negative != $y->is_negative;
  1259. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1260. }
  1261. static $zero;
  1262. if ( !isset($zero) ) {
  1263. $zero = new Math_BigInteger();
  1264. }
  1265. $x = $this->copy();
  1266. $y = $y->copy();
  1267. $x_sign = $x->is_negative;
  1268. $y_sign = $y->is_negative;
  1269. $x->is_negative = $y->is_negative = false;
  1270. $diff = $x->compare($y);
  1271. if ( !$diff ) {
  1272. $temp = new Math_BigInteger();
  1273. $temp->value = array(1);
  1274. $temp->is_negative = $x_sign != $y_sign;
  1275. return array($this->_normalize($temp), $this->_normalize(new Math_BigInteger()));
  1276. }
  1277. if ( $diff < 0 ) {
  1278. // if $x is negative, "add" $y.
  1279. if ( $x_sign ) {
  1280. $x = $y->subtract($x);
  1281. }
  1282. return array($this->_normalize(new Math_BigInteger()), $this->_normalize($x));
  1283. }
  1284. // normalize $x and $y as described in HAC 14.23 / 14…

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