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

/plugins/OStatus/extlib/phpseclib/Math/BigInteger.php

https://gitlab.com/windigo-gs/windigos-gnu-social
PHP | 3704 lines | 1969 code | 486 blank | 1249 comment | 398 complexity | 944ffe42723275b4d1cd93e27783e923 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, GPL-2.0

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

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

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