BigInteger.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. <?php
  2. namespace BI;
  3. if (!defined("S_MATH_BIGINTEGER_MODE")) {
  4. if (extension_loaded("gmp")) {
  5. define("S_MATH_BIGINTEGER_MODE", "gmp");
  6. }
  7. else if (extension_loaded("bcmath")) {
  8. define("S_MATH_BIGINTEGER_MODE", "bcmath");
  9. }
  10. else {
  11. if (!defined("S_MATH_BIGINTEGER_QUIET")) {
  12. throw new \Exception("Cannot use BigInteger. Neither gmp nor bcmath module is loaded");
  13. }
  14. }
  15. }
  16. if (S_MATH_BIGINTEGER_MODE == "gmp") {
  17. if (!extension_loaded("gmp")) {
  18. throw new \Exception("Extension gmp not loaded");
  19. }
  20. class BigInteger {
  21. public $value;
  22. public function __construct($value = 0, $base = 10) {
  23. $this->value = $base === true ? $value : BigInteger::getGmp($value, $base);
  24. }
  25. public static function createSafe($value = 0, $base = 10) {
  26. try {
  27. return new BigInteger($value, $base);
  28. }
  29. catch (\Exception $e) {
  30. return false;
  31. }
  32. }
  33. public static function isGmp($var) {
  34. if (is_resource($var)) {
  35. return get_resource_type($var) == "GMP integer";
  36. }
  37. if (class_exists("GMP") && $var instanceof \GMP) {
  38. return true;
  39. }
  40. return false;
  41. }
  42. public static function getGmp($value = 0, $base = 10) {
  43. if ($value instanceof BigInteger) {
  44. return $value->value;
  45. }
  46. if (BigInteger::isGmp($value)) {
  47. return $value;
  48. }
  49. $type = gettype($value);
  50. if ($type == "integer") {
  51. $gmp = gmp_init($value);
  52. if ($gmp === false) {
  53. throw new \Exception("Cannot initialize");
  54. }
  55. return $gmp;
  56. }
  57. if ($type == "string") {
  58. if ($base != 2 && $base != 10 && $base != 16 && $base != 256) {
  59. throw new \Exception("Unsupported BigInteger base");
  60. }
  61. if ($base == 256) {
  62. $value = bin2hex($value);
  63. $base = 16;
  64. }
  65. $level = error_reporting();
  66. error_reporting(0);
  67. $gmp = gmp_init($value, $base);
  68. error_reporting($level);
  69. if ($gmp === false) {
  70. throw new \Exception("Cannot initialize");
  71. }
  72. return $gmp;
  73. }
  74. throw new \Exception("Unsupported value, only string and integer are allowed, receive " . $type . ($type == "object" ? ", class: " . get_class($value) : ""));
  75. }
  76. public function toDec() {
  77. return gmp_strval($this->value, 10);
  78. }
  79. public function toHex() {
  80. $hex = gmp_strval($this->value, 16);
  81. return strlen($hex) % 2 == 1 ? "0". $hex : $hex;
  82. }
  83. public function toBytes() {
  84. return hex2bin($this->toHex());
  85. }
  86. public function toBase($base) {
  87. if ($base < 2 || $base > 62) {
  88. throw new \Exception("Invalid base");
  89. }
  90. return gmp_strval($this->value, $base);
  91. }
  92. public function toBits() {
  93. return gmp_strval($this->value, 2);
  94. }
  95. public function toString($base = 10) {
  96. if ($base == 2) {
  97. return $this->toBits();
  98. }
  99. if ($base == 10) {
  100. return $this->toDec();
  101. }
  102. if ($base == 16) {
  103. return $this->toHex();
  104. }
  105. if ($base == 256) {
  106. return $this->toBytes();
  107. }
  108. return $this->toBase($base);
  109. }
  110. public function __toString() {
  111. return $this->toString();
  112. }
  113. public function toNumber() {
  114. return gmp_intval($this->value);
  115. }
  116. public function add($x) {
  117. return new BigInteger(gmp_add($this->value, BigInteger::getGmp($x)), true);
  118. }
  119. public function sub($x) {
  120. return new BigInteger(gmp_sub($this->value, BigInteger::getGmp($x)), true);
  121. }
  122. public function mul($x) {
  123. return new BigInteger(gmp_mul($this->value, BigInteger::getGmp($x)), true);
  124. }
  125. public function div($x) {
  126. return new BigInteger(gmp_div_q($this->value, BigInteger::getGmp($x)), true);
  127. }
  128. public function divR($x) {
  129. return new BigInteger(gmp_div_r($this->value, BigInteger::getGmp($x)), true);
  130. }
  131. public function divQR($x) {
  132. $res = gmp_div_qr($this->value, BigInteger::getGmp($x));
  133. return array(new BigInteger($res[0], true), new BigInteger($res[1], true));
  134. }
  135. public function mod($x) {
  136. return new BigInteger(gmp_mod($this->value, BigInteger::getGmp($x)), true);
  137. }
  138. public function gcd($x) {
  139. return new BigInteger(gmp_gcd($this->value, BigInteger::getGmp($x)), true);
  140. }
  141. public function modInverse($x) {
  142. $res = gmp_invert($this->value, BigInteger::getGmp($x));
  143. return $res === false ? false : new BigInteger($res, true);
  144. }
  145. public function pow($x) {
  146. return new BigInteger(gmp_pow($this->value, (new BigInteger($x))->toNumber()), true);
  147. }
  148. public function powMod($x, $n) {
  149. return new BigInteger(gmp_powm($this->value, BigInteger::getGmp($x), BigInteger::getGmp($n)), true);
  150. }
  151. public function abs() {
  152. return new BigInteger(gmp_abs($this->value), true);
  153. }
  154. public function neg() {
  155. return new BigInteger(gmp_neg($this->value), true);
  156. }
  157. public function binaryAnd($x) {
  158. return new BigInteger(gmp_and($this->value, BigInteger::getGmp($x)), true);
  159. }
  160. public function binaryOr($x) {
  161. return new BigInteger(gmp_or($this->value, BigInteger::getGmp($x)), true);
  162. }
  163. public function binaryXor($x) {
  164. return new BigInteger(gmp_xor($this->value, BigInteger::getGmp($x)), true);
  165. }
  166. public function setbit($index, $bitOn = true) {
  167. $cpy = gmp_init(gmp_strval($this->value, 16), 16);
  168. gmp_setbit($cpy, $index, $bitOn);
  169. return new BigInteger($cpy, true);
  170. }
  171. public function testbit($index) {
  172. return gmp_testbit($this->value, $index);
  173. }
  174. public function scan0($start) {
  175. return gmp_scan0($this->value, $start);
  176. }
  177. public function scan1($start) {
  178. return gmp_scan1($this->value, $start);
  179. }
  180. public function cmp($x) {
  181. return gmp_cmp($this->value, BigInteger::getGmp($x));
  182. }
  183. public function equals($x) {
  184. return $this->cmp($x) === 0;
  185. }
  186. public function sign() {
  187. return gmp_sign($this->value);
  188. }
  189. }
  190. }
  191. else if (S_MATH_BIGINTEGER_MODE == "bcmath") {
  192. if (!extension_loaded("bcmath")) {
  193. throw new \Exception("Extension bcmath not loaded");
  194. }
  195. class BigInteger{
  196. public static $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv";
  197. public $value;
  198. public function __construct($value = 0, $base = 10) {
  199. $this->value = $base === true ? $value : BigInteger::getBC($value, $base);
  200. }
  201. public static function createSafe($value = 0, $base = 10) {
  202. try {
  203. return new BigInteger($value, $base);
  204. }
  205. catch (\Exception $e) {
  206. return false;
  207. }
  208. }
  209. public static function checkBinary($str) {
  210. $len = strlen($str);
  211. for ($i = 0; $i < $len; $i++) {
  212. $c = ord($str[$i]);
  213. if (($i != 0 || $c != 45) && ($c < 48 || $c > 49)) {
  214. return false;
  215. }
  216. }
  217. return true;
  218. }
  219. public static function checkDecimal($str) {
  220. $len = strlen($str);
  221. for ($i = 0; $i < $len; $i++) {
  222. $c = ord($str[$i]);
  223. if (($i != 0 || $c != 45) && ($c < 48 || $c > 57)) {
  224. return false;
  225. }
  226. }
  227. return true;
  228. }
  229. public static function checkHex($str) {
  230. $len = strlen($str);
  231. for ($i = 0; $i < $len; $i++) {
  232. $c = ord($str[$i]);
  233. if (($i != 0 || $c != 45) && ($c < 48 || $c > 57) && ($c < 65 || $c > 70) && ($c < 97 || $c > 102)) {
  234. return false;
  235. }
  236. }
  237. return true;
  238. }
  239. public static function getBC($value = 0, $base = 10) {
  240. if ($value instanceof BigInteger) {
  241. return $value->value;
  242. }
  243. $type = gettype($value);
  244. if ($type == "integer") {
  245. return strval($value);
  246. }
  247. if ($type == "string") {
  248. if ($base == 2) {
  249. $value = str_replace(" ", "", $value);
  250. if (!BigInteger::checkBinary($value)) {
  251. throw new \Exception("Invalid characters");
  252. }
  253. $minus = $value[0] == "-";
  254. if ($minus) {
  255. $value = substr($value, 1);
  256. }
  257. $len = strlen($value);
  258. $m = 1;
  259. $res = "0";
  260. for ($i = $len - 1; $i >= 0; $i -= 8) {
  261. $h = $i - 7 < 0 ? substr($value, 0, $i + 1) : substr($value, $i - 7, 8);
  262. $res = bcadd($res, bcmul(bindec($h), $m, 0), 0);
  263. $m = bcmul($m, "256", 0);
  264. }
  265. return ($minus ? "-" : "") . $res;
  266. }
  267. if ($base == 10) {
  268. $value = str_replace(" ", "", $value);
  269. if (!BigInteger::checkDecimal($value)) {
  270. throw new \Exception("Invalid characters");
  271. }
  272. return $value;
  273. }
  274. if ($base == 16) {
  275. $value = str_replace(" ", "", $value);
  276. if (!BigInteger::checkHex($value)) {
  277. throw new \Exception("Invalid characters");
  278. }
  279. $minus = $value[0] == "-";
  280. if ($minus) {
  281. $value = substr($value, 1);
  282. }
  283. $len = strlen($value);
  284. $m = 1;
  285. $res = "0";
  286. for ($i = $len - 1; $i >= 0; $i -= 2) {
  287. $h = $i == 0 ? "0" . substr($value, 0, 1) : substr($value, $i - 1, 2);
  288. $res = bcadd($res, bcmul(hexdec($h), $m, 0), 0);
  289. $m = bcmul($m, "256", 0);
  290. }
  291. return ($minus ? "-" : "") . $res;
  292. }
  293. if ($base == 256) {
  294. $len = strlen($value);
  295. $m = 1;
  296. $res = "0";
  297. for ($i = $len - 1; $i >= 0; $i -= 6) {
  298. $h = $i - 5 < 0 ? substr($value, 0, $i + 1) : substr($value, $i - 5, 6);
  299. $res = bcadd($res, bcmul(base_convert(bin2hex($h), 16, 10), $m, 0), 0);
  300. $m = bcmul($m, "281474976710656", 0);
  301. }
  302. return $res;
  303. }
  304. throw new \Exception("Unsupported BigInteger base");
  305. }
  306. throw new \Exception("Unsupported value, only string and integer are allowed, receive " . $type . ($type == "object" ? ", class: " . get_class($value) : ""));
  307. }
  308. public function toDec() {
  309. return $this->value;
  310. }
  311. public function toHex() {
  312. return bin2hex($this->toBytes());
  313. }
  314. public function toBytes() {
  315. $value = "";
  316. $current = $this->value;
  317. if ($current[0] == "-") {
  318. $current = substr($current, 1);
  319. }
  320. while (bccomp($current, "0", 0) > 0) {
  321. $temp = bcmod($current, "281474976710656");
  322. $value = hex2bin(str_pad(base_convert($temp, 10, 16), 12, "0", STR_PAD_LEFT)) . $value;
  323. $current = bcdiv($current, "281474976710656", 0);
  324. }
  325. return ltrim($value, chr(0));
  326. }
  327. public function toBase($base) {
  328. if ($base < 2 || $base > 62) {
  329. throw new \Exception("Invalid base");
  330. }
  331. $value = '';
  332. $current = $this->value;
  333. $base = BigInteger::getBC($base);
  334. if ($current[0] == '-') {
  335. $current = substr($current, 1);
  336. }
  337. while (bccomp($current, '0', 0) > 0) {
  338. $v = bcmod($current, $base);
  339. $value = BigInteger::$chars[$v] . $value;
  340. $current = bcdiv($current, $base, 0);
  341. }
  342. return $value;
  343. }
  344. public function toBits() {
  345. $bytes = $this->toBytes();
  346. $res = "";
  347. $len = strlen($bytes);
  348. for ($i = 0; $i < $len; $i++) {
  349. $b = decbin(ord($bytes[$i]));
  350. $res .= strlen($b) != 8 ? str_pad($b, 8, "0", STR_PAD_LEFT) : $b;
  351. }
  352. $res = ltrim($res, "0");
  353. return strlen($res) == 0 ? "0" : $res;
  354. }
  355. public function toString($base = 10) {
  356. if ($base == 2) {
  357. return $this->toBits();
  358. }
  359. if ($base == 10) {
  360. return $this->toDec();
  361. }
  362. if ($base == 16) {
  363. return $this->toHex();
  364. }
  365. if ($base == 256) {
  366. return $this->toBytes();
  367. }
  368. return $this->toBase($base);
  369. }
  370. public function __toString() {
  371. return $this->toString();
  372. }
  373. public function toNumber() {
  374. return intval($this->value);
  375. }
  376. public function add($x) {
  377. return new BigInteger(bcadd($this->value, BigInteger::getBC($x), 0), true);
  378. }
  379. public function sub($x) {
  380. return new BigInteger(bcsub($this->value, BigInteger::getBC($x), 0), true);
  381. }
  382. public function mul($x) {
  383. return new BigInteger(bcmul($this->value, BigInteger::getBC($x), 0), true);
  384. }
  385. public function div($x) {
  386. return new BigInteger(bcdiv($this->value, BigInteger::getBC($x), 0), true);
  387. }
  388. public function divR($x) {
  389. return new BigInteger(bcmod($this->value, BigInteger::getBC($x)), true);
  390. }
  391. public function divQR($x) {
  392. return array(
  393. $this->div($x),
  394. $this->divR($x)
  395. );
  396. }
  397. public function mod($x) {
  398. $xv = BigInteger::getBC($x);
  399. $mod = bcmod($this->value, $xv);
  400. if ($mod[0] == "-") {
  401. $mod = bcadd($mod, $xv[0] == "-" ? substr($xv, 1) : $xv, 0);
  402. }
  403. return new BigInteger($mod, true);
  404. }
  405. public function extendedGcd($n) {
  406. $u = $this->value;
  407. $v = (new BigInteger($n))->abs()->value;
  408. $a = "1";
  409. $b = "0";
  410. $c = "0";
  411. $d = "1";
  412. while (bccomp($v, "0", 0) != 0) {
  413. $q = bcdiv($u, $v, 0);
  414. $temp = $u;
  415. $u = $v;
  416. $v = bcsub($temp, bcmul($v, $q, 0), 0);
  417. $temp = $a;
  418. $a = $c;
  419. $c = bcsub($temp, bcmul($a, $q, 0), 0);
  420. $temp = $b;
  421. $b = $d;
  422. $d = bcsub($temp, bcmul($b, $q, 0), 0);
  423. }
  424. return array(
  425. "gcd" => new BigInteger($u, true),
  426. "x" => new BigInteger($a, true),
  427. "y" => new BigInteger($b, true)
  428. );
  429. }
  430. public function gcd($x) {
  431. return $this->extendedGcd($x)["gcd"];
  432. }
  433. public function modInverse($n) {
  434. $n = (new BigInteger($n))->abs();
  435. if ($this->sign() < 0) {
  436. $temp = $this->abs();
  437. $temp = $temp->modInverse($n);
  438. return $n->sub($temp);
  439. }
  440. extract($this->extendedGcd($n));
  441. if (!$gcd->equals(1)) {
  442. return false;
  443. }
  444. $x = $x->sign() < 0 ? $x->add($n) : $x;
  445. return $this->sign() < 0 ? $n->sub($x) : $x;
  446. }
  447. public function pow($x) {
  448. return new BigInteger(bcpow($this->value, BigInteger::getBC($x), 0), true);
  449. }
  450. public function powMod($x, $n) {
  451. return new BigInteger(bcpowmod($this->value, BigInteger::getBC($x), BigInteger::getBC($n), 0), true);
  452. }
  453. public function abs() {
  454. return new BigInteger($this->value[0] == "-" ? substr($this->value, 1) : $this->value, true);
  455. }
  456. public function neg() {
  457. return new BigInteger($this->value[0] == "-" ? substr($this->value, 1) : "-" . $this->value, true);
  458. }
  459. public function binaryAnd($x) {
  460. $left = $this->toBytes();
  461. $right = (new BigInteger($x))->toBytes();
  462. $length = max(strlen($left), strlen($right));
  463. $left = str_pad($left, $length, chr(0), STR_PAD_LEFT);
  464. $right = str_pad($right, $length, chr(0), STR_PAD_LEFT);
  465. return new BigInteger($left & $right, 256);
  466. }
  467. public function binaryOr($x) {
  468. $left = $this->toBytes();
  469. $right = (new BigInteger($x))->toBytes();
  470. $length = max(strlen($left), strlen($right));
  471. $left = str_pad($left, $length, chr(0), STR_PAD_LEFT);
  472. $right = str_pad($right, $length, chr(0), STR_PAD_LEFT);
  473. return new BigInteger($left | $right, 256);
  474. }
  475. public function binaryXor($x) {
  476. $left = $this->toBytes();
  477. $right = (new BigInteger($x))->toBytes();
  478. $length = max(strlen($left), strlen($right));
  479. $left = str_pad($left, $length, chr(0), STR_PAD_LEFT);
  480. $right = str_pad($right, $length, chr(0), STR_PAD_LEFT);
  481. return new BigInteger($left ^ $right, 256);
  482. }
  483. public function setbit($index, $bitOn = true) {
  484. $bits = $this->toBits();
  485. $bits[strlen($bits) - $index - 1] = $bitOn ? "1" : "0";
  486. return new BigInteger($bits, 2);
  487. }
  488. public function testbit($index) {
  489. $bytes = $this->toBytes();
  490. $bytesIndex = intval($index / 8);
  491. $len = strlen($bytes);
  492. $b = $bytesIndex >= $len ? 0 : ord($bytes[$len - $bytesIndex - 1]);
  493. $v = 1 << ($index % 8);
  494. return ($b & $v) === $v;
  495. }
  496. public function scan0($start) {
  497. $bits = $this->toBits();
  498. $len = strlen($bits);
  499. if ($start < 0 || $start >= $len) {
  500. return -1;
  501. }
  502. $pos = strrpos($bits, "0", -1 - $start);
  503. return $pos === false ? -1 : $len - $pos - 1;
  504. }
  505. public function scan1($start) {
  506. $bits = $this->toBits();
  507. $len = strlen($bits);
  508. if ($start < 0 || $start >= $len) {
  509. return -1;
  510. }
  511. $pos = strrpos($bits, "1", -1 - $start);
  512. return $pos === false ? -1 : $len - $pos - 1;
  513. }
  514. public function cmp($x) {
  515. return bccomp($this->value, BigInteger::getBC($x));
  516. }
  517. public function equals($x) {
  518. return $this->value === BigInteger::getBC($x);
  519. }
  520. public function sign() {
  521. return $this->value[0] === "-" ? -1 : ($this->value === "0" ? 0 : 1);
  522. }
  523. }
  524. }
  525. else {
  526. if (!defined("S_MATH_BIGINTEGER_QUIET")) {
  527. throw new \Exception("Unsupported S_MATH_BIGINTEGER_MODE " . S_MATH_BIGINTEGER_MODE);
  528. }
  529. }