BigInt.hpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761
  1. /*
  2. BigInt
  3. ------
  4. Arbitrary-sized integer class for C++.
  5. Version: 0.4.0-dev
  6. Released on: 03 January 2018 10:51 IST
  7. Author: Syed Faheel Ahmad (faheel@live.in)
  8. Project on GitHub: https://github.com/faheel/BigInt
  9. License: MIT
  10. */
  11. /*
  12. ===========================================================================
  13. BigInt
  14. ===========================================================================
  15. Definition for the BigInt class.
  16. */
  17. #ifndef BIG_INT_HPP
  18. #define BIG_INT_HPP
  19. #include <iostream>
  20. class BigInt {
  21. std::string value;
  22. char sign;
  23. public:
  24. // Constructors:
  25. BigInt();
  26. BigInt(const BigInt&);
  27. BigInt(const long long&);
  28. BigInt(const std::string&);
  29. // Assignment operators:
  30. BigInt& operator=(const BigInt&);
  31. BigInt& operator=(const long long&);
  32. BigInt& operator=(const std::string&);
  33. // Unary arithmetic operators:
  34. BigInt operator+() const; // unary +
  35. BigInt operator-() const; // unary -
  36. // Binary arithmetic operators:
  37. BigInt operator+(const BigInt&) const;
  38. BigInt operator-(const BigInt&) const;
  39. BigInt operator*(const BigInt&) const;
  40. BigInt operator/(const BigInt&) const;
  41. BigInt operator%(const BigInt&) const;
  42. BigInt operator+(const long long&) const;
  43. BigInt operator-(const long long&) const;
  44. BigInt operator*(const long long&) const;
  45. BigInt operator/(const long long&) const;
  46. BigInt operator%(const long long&) const;
  47. BigInt operator+(const std::string&) const;
  48. BigInt operator-(const std::string&) const;
  49. BigInt operator*(const std::string&) const;
  50. BigInt operator/(const std::string&) const;
  51. BigInt operator%(const std::string&) const;
  52. // Arithmetic-assignment operators:
  53. BigInt& operator+=(const BigInt&);
  54. BigInt& operator-=(const BigInt&);
  55. BigInt& operator*=(const BigInt&);
  56. BigInt& operator/=(const BigInt&);
  57. BigInt& operator%=(const BigInt&);
  58. BigInt& operator+=(const long long&);
  59. BigInt& operator-=(const long long&);
  60. BigInt& operator*=(const long long&);
  61. BigInt& operator/=(const long long&);
  62. BigInt& operator%=(const long long&);
  63. BigInt& operator+=(const std::string&);
  64. BigInt& operator-=(const std::string&);
  65. BigInt& operator*=(const std::string&);
  66. BigInt& operator/=(const std::string&);
  67. BigInt& operator%=(const std::string&);
  68. // Increment and decrement operators:
  69. BigInt& operator++(); // pre-increment
  70. BigInt& operator--(); // pre-decrement
  71. BigInt operator++(int); // post-increment
  72. BigInt operator--(int); // post-decrement
  73. // Relational operators:
  74. bool operator<(const BigInt&) const;
  75. bool operator>(const BigInt&) const;
  76. bool operator<=(const BigInt&) const;
  77. bool operator>=(const BigInt&) const;
  78. bool operator==(const BigInt&) const;
  79. bool operator!=(const BigInt&) const;
  80. bool operator<(const long long&) const;
  81. bool operator>(const long long&) const;
  82. bool operator<=(const long long&) const;
  83. bool operator>=(const long long&) const;
  84. bool operator==(const long long&) const;
  85. bool operator!=(const long long&) const;
  86. bool operator<(const std::string&) const;
  87. bool operator>(const std::string&) const;
  88. bool operator<=(const std::string&) const;
  89. bool operator>=(const std::string&) const;
  90. bool operator==(const std::string&) const;
  91. bool operator!=(const std::string&) const;
  92. // I/O stream operators:
  93. friend std::istream& operator>>(std::istream&, BigInt&);
  94. friend std::ostream& operator<<(std::ostream&, const BigInt&);
  95. // Conversion functions:
  96. std::string to_string() const;
  97. int to_int() const;
  98. long to_long() const;
  99. long long to_long_long() const;
  100. };
  101. #endif // BIG_INT_HPP
  102. /*
  103. ===========================================================================
  104. Utility functions
  105. ===========================================================================
  106. */
  107. #ifndef BIG_INT_UTILITY_FUNCTIONS_HPP
  108. #define BIG_INT_UTILITY_FUNCTIONS_HPP
  109. #include <tuple>
  110. /*
  111. is_valid_number
  112. ---------------
  113. Checks whether the given string is a valid integer.
  114. */
  115. bool is_valid_number(const std::string& num) {
  116. for (char digit : num)
  117. if (digit < '0' or digit > '9')
  118. return false;
  119. return true;
  120. }
  121. /*
  122. strip_leading_zeroes
  123. --------------------
  124. Strip the leading zeroes from a number represented as a string.
  125. */
  126. void strip_leading_zeroes(std::string& num) {
  127. size_t i;
  128. for (i = 0; i < num.size(); i++)
  129. if (num[i] != '0')
  130. break;
  131. if (i == num.size())
  132. num = "0";
  133. else
  134. num = num.substr(i);
  135. }
  136. /*
  137. add_leading_zeroes
  138. ------------------
  139. Adds a given number of leading zeroes to a string-represented integer `num`.
  140. */
  141. void add_leading_zeroes(std::string& num, size_t num_zeroes) {
  142. num = std::string(num_zeroes, '0') + num;
  143. }
  144. /*
  145. add_trailing_zeroes
  146. -------------------
  147. Adds a given number of trailing zeroes to a string-represented integer `num`.
  148. */
  149. void add_trailing_zeroes(std::string& num, size_t num_zeroes) {
  150. num += std::string(num_zeroes, '0');
  151. }
  152. /*
  153. get_larger_and_smaller
  154. ----------------------
  155. Identifies the given string-represented integers as `larger` and `smaller`,
  156. padding the smaller number with leading zeroes to make it equal in length to
  157. the larger number.
  158. */
  159. std::tuple<std::string, std::string> get_larger_and_smaller(const std::string& num1,
  160. const std::string& num2) {
  161. std::string larger, smaller;
  162. if (num1.size() > num2.size() or
  163. (num1.size() == num2.size() and num1 > num2)) {
  164. larger = num1;
  165. smaller = num2;
  166. }
  167. else {
  168. larger = num2;
  169. smaller = num1;
  170. }
  171. // pad the smaller number with zeroes
  172. add_leading_zeroes(smaller, larger.size() - smaller.size());
  173. return std::make_tuple(larger, smaller);
  174. }
  175. #endif // BIG_INT_UTILITY_FUNCTIONS_HPP
  176. /*
  177. ===========================================================================
  178. Constructors
  179. ===========================================================================
  180. */
  181. #ifndef BIG_INT_CONSTRUCTORS_HPP
  182. #define BIG_INT_CONSTRUCTORS_HPP
  183. /*
  184. Default constructor
  185. -------------------
  186. */
  187. BigInt::BigInt() {
  188. value = "0";
  189. sign = '+';
  190. }
  191. /*
  192. Copy constructor
  193. ----------------
  194. */
  195. BigInt::BigInt(const BigInt& num) {
  196. value = num.value;
  197. sign = num.sign;
  198. }
  199. /*
  200. Integer to BigInt
  201. -----------------
  202. */
  203. BigInt::BigInt(const long long& num) {
  204. value = std::to_string(num);
  205. if (num < 0) {
  206. sign = '-';
  207. value = value.substr(1); // remove minus sign from value
  208. }
  209. else
  210. sign = '+';
  211. }
  212. /*
  213. String to BigInt
  214. ----------------
  215. */
  216. BigInt::BigInt(const std::string& num) {
  217. if (num[0] == '+' or num[0] == '-') { // check for sign
  218. std::string magnitude = num.substr(1);
  219. if (is_valid_number(magnitude)) {
  220. value = magnitude;
  221. sign = num[0];
  222. }
  223. else {
  224. throw std::invalid_argument("Expected an integer, got \'" + num + "\'");
  225. }
  226. }
  227. else { // if no sign is specified
  228. if (is_valid_number(num)) {
  229. value = num;
  230. sign = '+'; // positive by default
  231. }
  232. else {
  233. throw std::invalid_argument("Expected an integer, got \'" + num + "\'");
  234. }
  235. }
  236. strip_leading_zeroes(value);
  237. }
  238. #endif // BIG_INT_CONSTRUCTORS_HPP
  239. /*
  240. ===========================================================================
  241. Conversion functions for BigInt
  242. ===========================================================================
  243. */
  244. #ifndef BIG_INT_CONVERSION_FUNCTIONS_HPP
  245. #define BIG_INT_CONVERSION_FUNCTIONS_HPP
  246. /*
  247. to_string
  248. ---------
  249. Converts a BigInt to a string.
  250. */
  251. std::string BigInt::to_string() const {
  252. // prefix with sign if negative
  253. return this->sign == '-' ? "-" + this->value : this->value;
  254. }
  255. /*
  256. to_int
  257. ------
  258. Converts a BigInt to an int.
  259. NOTE: If the BigInt is out of range of an int, stoi() will throw an
  260. out_of_range exception.
  261. */
  262. int BigInt::to_int() const {
  263. return std::stoi(this->to_string());
  264. }
  265. /*
  266. to_long
  267. -------
  268. Converts a BigInt to a long int.
  269. NOTE: If the BigInt is out of range of a long int, stol() will throw an
  270. out_of_range exception.
  271. */
  272. long BigInt::to_long() const {
  273. return std::stol(this->to_string());
  274. }
  275. /*
  276. to_long_long
  277. ------------
  278. Converts a BigInt to a long long int.
  279. NOTE: If the BigInt is out of range of a long long int, stoll() will throw
  280. an out_of_range exception.
  281. */
  282. long long BigInt::to_long_long() const {
  283. return std::stoll(this->to_string());
  284. }
  285. #endif // BIG_INT_CONVERSION_FUNCTIONS_HPP
  286. /*
  287. ===========================================================================
  288. Assignment operators
  289. ===========================================================================
  290. */
  291. #ifndef BIG_INT_ASSIGNMENT_OPERATORS_HPP
  292. #define BIG_INT_ASSIGNMENT_OPERATORS_HPP
  293. /*
  294. BigInt = BigInt
  295. ---------------
  296. */
  297. BigInt& BigInt::operator=(const BigInt& num) {
  298. value = num.value;
  299. sign = num.sign;
  300. return *this;
  301. }
  302. /*
  303. BigInt = Integer
  304. ----------------
  305. */
  306. BigInt& BigInt::operator=(const long long& num) {
  307. BigInt temp(num);
  308. value = temp.value;
  309. sign = temp.sign;
  310. return *this;
  311. }
  312. /*
  313. BigInt = String
  314. ---------------
  315. */
  316. BigInt& BigInt::operator=(const std::string& num) {
  317. BigInt temp(num);
  318. value = temp.value;
  319. sign = temp.sign;
  320. return *this;
  321. }
  322. #endif // BIG_INT_ASSIGNMENT_OPERATORS_HPP
  323. /*
  324. ===========================================================================
  325. Unary arithmetic operators
  326. ===========================================================================
  327. */
  328. #ifndef BIG_INT_UNARY_ARITHMETIC_OPERATORS_HPP
  329. #define BIG_INT_UNARY_ARITHMETIC_OPERATORS_HPP
  330. /*
  331. +BigInt
  332. -------
  333. Returns the value of a BigInt.
  334. NOTE: This function does not return the absolute value. To get the absolute
  335. value of a BigInt, use the `abs` function.
  336. */
  337. BigInt BigInt::operator+() const {
  338. return *this;
  339. }
  340. /*
  341. -BigInt
  342. -------
  343. Returns the negative of a BigInt.
  344. */
  345. BigInt BigInt::operator-() const {
  346. BigInt temp;
  347. temp.value = value;
  348. if (value != "0") {
  349. if (sign == '+')
  350. temp.sign = '-';
  351. else
  352. temp.sign = '+';
  353. }
  354. return temp;
  355. }
  356. #endif // BIG_INT_UNARY_ARITHMETIC_OPERATORS_HPP
  357. /*
  358. ===========================================================================
  359. Relational operators
  360. ===========================================================================
  361. All operators depend on the '<' and/or '==' operator(s).
  362. */
  363. #ifndef BIG_INT_RELATIONAL_OPERATORS_HPP
  364. #define BIG_INT_RELATIONAL_OPERATORS_HPP
  365. /*
  366. BigInt == BigInt
  367. ----------------
  368. */
  369. bool BigInt::operator==(const BigInt& num) const {
  370. return (sign == num.sign) and (value == num.value);
  371. }
  372. /*
  373. BigInt != BigInt
  374. ----------------
  375. */
  376. bool BigInt::operator!=(const BigInt& num) const {
  377. return !(*this == num);
  378. }
  379. /*
  380. BigInt < BigInt
  381. ---------------
  382. */
  383. bool BigInt::operator<(const BigInt& num) const {
  384. if (sign == num.sign) {
  385. if (sign == '+') {
  386. if (value.length() == num.value.length())
  387. return value < num.value;
  388. else
  389. return value.length() < num.value.length();
  390. }
  391. else
  392. return -(*this) > -num;
  393. }
  394. else
  395. return sign == '-';
  396. }
  397. /*
  398. BigInt > BigInt
  399. ---------------
  400. */
  401. bool BigInt::operator>(const BigInt& num) const {
  402. return !((*this < num) or (*this == num));
  403. }
  404. /*
  405. BigInt <= BigInt
  406. ----------------
  407. */
  408. bool BigInt::operator<=(const BigInt& num) const {
  409. return (*this < num) or (*this == num);
  410. }
  411. /*
  412. BigInt >= BigInt
  413. ----------------
  414. */
  415. bool BigInt::operator>=(const BigInt& num) const {
  416. return !(*this < num);
  417. }
  418. /*
  419. BigInt == Integer
  420. -----------------
  421. */
  422. bool BigInt::operator==(const long long& num) const {
  423. return *this == BigInt(num);
  424. }
  425. /*
  426. Integer == BigInt
  427. -----------------
  428. */
  429. bool operator==(const long long& lhs, const BigInt& rhs) {
  430. return BigInt(lhs) == rhs;
  431. }
  432. /*
  433. BigInt != Integer
  434. -----------------
  435. */
  436. bool BigInt::operator!=(const long long& num) const {
  437. return !(*this == BigInt(num));
  438. }
  439. /*
  440. Integer != BigInt
  441. -----------------
  442. */
  443. bool operator!=(const long long& lhs, const BigInt& rhs) {
  444. return BigInt(lhs) != rhs;
  445. }
  446. /*
  447. BigInt < Integer
  448. ----------------
  449. */
  450. bool BigInt::operator<(const long long& num) const {
  451. return *this < BigInt(num);
  452. }
  453. /*
  454. Integer < BigInt
  455. ----------------
  456. */
  457. bool operator<(const long long& lhs, const BigInt& rhs) {
  458. return BigInt(lhs) < rhs;
  459. }
  460. /*
  461. BigInt > Integer
  462. ----------------
  463. */
  464. bool BigInt::operator>(const long long& num) const {
  465. return *this > BigInt(num);
  466. }
  467. /*
  468. Integer > BigInt
  469. ----------------
  470. */
  471. bool operator>(const long long& lhs, const BigInt& rhs) {
  472. return BigInt(lhs) > rhs;
  473. }
  474. /*
  475. BigInt <= Integer
  476. -----------------
  477. */
  478. bool BigInt::operator<=(const long long& num) const {
  479. return !(*this > BigInt(num));
  480. }
  481. /*
  482. Integer <= BigInt
  483. -----------------
  484. */
  485. bool operator<=(const long long& lhs, const BigInt& rhs) {
  486. return BigInt(lhs) <= rhs;
  487. }
  488. /*
  489. BigInt >= Integer
  490. -----------------
  491. */
  492. bool BigInt::operator>=(const long long& num) const {
  493. return !(*this < BigInt(num));
  494. }
  495. /*
  496. Integer >= BigInt
  497. -----------------
  498. */
  499. bool operator>=(const long long& lhs, const BigInt& rhs) {
  500. return BigInt(lhs) >= rhs;
  501. }
  502. /*
  503. BigInt == String
  504. ----------------
  505. */
  506. bool BigInt::operator==(const std::string& num) const {
  507. return *this == BigInt(num);
  508. }
  509. /*
  510. String == BigInt
  511. ----------------
  512. */
  513. bool operator==(const std::string& lhs, const BigInt& rhs) {
  514. return BigInt(lhs) == rhs;
  515. }
  516. /*
  517. BigInt != String
  518. ----------------
  519. */
  520. bool BigInt::operator!=(const std::string& num) const {
  521. return !(*this == BigInt(num));
  522. }
  523. /*
  524. String != BigInt
  525. ----------------
  526. */
  527. bool operator!=(const std::string& lhs, const BigInt& rhs) {
  528. return BigInt(lhs) != rhs;
  529. }
  530. /*
  531. BigInt < String
  532. ---------------
  533. */
  534. bool BigInt::operator<(const std::string& num) const {
  535. return *this < BigInt(num);
  536. }
  537. /*
  538. String < BigInt
  539. ---------------
  540. */
  541. bool operator<(const std::string& lhs, const BigInt& rhs) {
  542. return BigInt(lhs) < rhs;
  543. }
  544. /*
  545. BigInt > String
  546. ---------------
  547. */
  548. bool BigInt::operator>(const std::string& num) const {
  549. return *this > BigInt(num);
  550. }
  551. /*
  552. String > BigInt
  553. ---------------
  554. */
  555. bool operator>(const std::string& lhs, const BigInt& rhs) {
  556. return BigInt(lhs) > rhs;
  557. }
  558. /*
  559. BigInt <= String
  560. ----------------
  561. */
  562. bool BigInt::operator<=(const std::string& num) const {
  563. return !(*this > BigInt(num));
  564. }
  565. /*
  566. String <= BigInt
  567. ----------------
  568. */
  569. bool operator<=(const std::string& lhs, const BigInt& rhs) {
  570. return BigInt(lhs) <= rhs;
  571. }
  572. /*
  573. BigInt >= String
  574. ----------------
  575. */
  576. bool BigInt::operator>=(const std::string& num) const {
  577. return !(*this < BigInt(num));
  578. }
  579. /*
  580. String >= BigInt
  581. ----------------
  582. */
  583. bool operator>=(const std::string& lhs, const BigInt& rhs) {
  584. return BigInt(lhs) >= rhs;
  585. }
  586. #endif // BIG_INT_RELATIONAL_OPERATORS_HPP
  587. /*
  588. ===========================================================================
  589. Math functions for BigInt
  590. ===========================================================================
  591. */
  592. #ifndef BIG_INT_MATH_FUNCTIONS_HPP
  593. #define BIG_INT_MATH_FUNCTIONS_HPP
  594. #include <string>
  595. /*
  596. abs
  597. ---
  598. Returns the absolute value of a BigInt.
  599. */
  600. BigInt abs(const BigInt& num) {
  601. return num < 0 ? -num : num;
  602. }
  603. /*
  604. big_pow10
  605. ---------
  606. Returns a BigInt equal to 10^exp.
  607. NOTE: exponent should be a non-negative integer.
  608. */
  609. BigInt big_pow10(size_t exp) {
  610. return BigInt("1" + std::string(exp, '0'));
  611. }
  612. /*
  613. pow (BigInt)
  614. ------------
  615. Returns a BigInt equal to base^exp.
  616. */
  617. BigInt pow(const BigInt& base, unsigned int exp) {
  618. if (exp < 0) {
  619. if (base == 0)
  620. throw std::logic_error("Cannot divide by zero");
  621. return abs(base) == 1 ? base : 0;
  622. }
  623. if (exp == 0) {
  624. if (base == 0)
  625. throw std::logic_error("Zero cannot be raised to zero");
  626. return 1;
  627. }
  628. BigInt result = base, result_odd = 1;
  629. while (exp > 1) {
  630. if (exp % 2)
  631. result_odd *= result;
  632. result *= result;
  633. exp /= 2;
  634. }
  635. return result * result_odd;
  636. }
  637. BigInt modpow(const BigInt& base, const BigInt& exp, const BigInt& mod) {
  638. if (exp < 0) {
  639. if (base == 0)
  640. throw std::logic_error("Cannot divide by zero");
  641. return abs(base) == 1 ? base : 0;
  642. }
  643. if (exp == 0) {
  644. if (base == 0)
  645. throw std::logic_error("Zero cannot be raised to zero");
  646. return 1;
  647. }
  648. BigInt result = base, result_odd = 1;
  649. while (exp > 1) {
  650. if (exp % 2 == 0)
  651. result_odd *= result;
  652. result *= result;
  653. exp /= 2;
  654. }
  655. return result * result_odd;
  656. }
  657. /*
  658. pow (Integer)
  659. -------------
  660. Returns a BigInt equal to base^exp.
  661. */
  662. BigInt pow(const long long& base, int exp) {
  663. return pow(BigInt(base), exp);
  664. }
  665. /*
  666. pow (String)
  667. ------------
  668. Returns a BigInt equal to base^exp.
  669. */
  670. BigInt pow(const std::string& base, int exp) {
  671. return pow(BigInt(base), exp);
  672. }
  673. /*
  674. sqrt
  675. ----
  676. Returns the positive integer square root of a BigInt using Newton's method.
  677. NOTE: the input must be non-negative.
  678. */
  679. BigInt sqrt(const BigInt& num) {
  680. if (num < 0)
  681. throw std::invalid_argument("Cannot compute square root of a negative integer");
  682. // Optimisations for small inputs:
  683. if (num == 0)
  684. return 0;
  685. else if (num < 4)
  686. return 1;
  687. else if (num < 9)
  688. return 2;
  689. else if (num < 16)
  690. return 3;
  691. BigInt sqrt_prev = 0;
  692. // The value for `sqrt_current` is chosen close to that of the actual
  693. // square root.
  694. // Since a number's square root has at least one less than half as many
  695. // digits as the number,
  696. // sqrt_current = 10^(half_the_digits_in_num - 1)
  697. BigInt sqrt_current = big_pow10(num.to_string().size() / 2 - 1);
  698. while (abs(sqrt_current - sqrt_prev) > 1) {
  699. sqrt_prev = sqrt_current;
  700. sqrt_current = (num / sqrt_prev + sqrt_prev) / 2;
  701. }
  702. return sqrt_current;
  703. }
  704. #endif // BIG_INT_MATH_FUNCTIONS_HPP
  705. /*
  706. ===========================================================================
  707. Binary arithmetic operators
  708. ===========================================================================
  709. */
  710. #ifndef BIG_INT_BINARY_ARITHMETIC_OPERATORS_HPP
  711. #define BIG_INT_BINARY_ARITHMETIC_OPERATORS_HPP
  712. #include <climits>
  713. #include <cmath>
  714. #include <string>
  715. const long long FLOOR_SQRT_LLONG_MAX = 3037000499;
  716. /*
  717. BigInt + BigInt
  718. ---------------
  719. The operand on the RHS of the addition is `num`.
  720. */
  721. BigInt BigInt::operator+(const BigInt& num) const {
  722. // if the operands are of opposite signs, perform subtraction
  723. if (this->sign == '+' and num.sign == '-') {
  724. BigInt rhs = num;
  725. rhs.sign = '+';
  726. return *this - rhs;
  727. }
  728. else if (this->sign == '-' and num.sign == '+') {
  729. BigInt lhs = *this;
  730. lhs.sign = '+';
  731. return -(lhs - num);
  732. }
  733. // identify the numbers as `larger` and `smaller`
  734. std::string larger, smaller;
  735. std::tie(larger, smaller) = get_larger_and_smaller(this->value, num.value);
  736. BigInt result; // the resultant sum
  737. result.value = ""; // the value is cleared as the digits will be appended
  738. short carry = 0, sum;
  739. // add the two values
  740. for (long i = larger.size() - 1; i >= 0; i--) {
  741. sum = larger[i] - '0' + smaller[i] - '0' + carry;
  742. result.value = std::to_string(sum % 10) + result.value;
  743. carry = sum / (short) 10;
  744. }
  745. if (carry)
  746. result.value = std::to_string(carry) + result.value;
  747. // if the operands are negative, the result is negative
  748. if (this->sign == '-' and result.value != "0")
  749. result.sign = '-';
  750. return result;
  751. }
  752. /*
  753. BigInt - BigInt
  754. ---------------
  755. The operand on the RHS of the subtraction is `num`.
  756. */
  757. BigInt BigInt::operator-(const BigInt& num) const {
  758. // if the operands are of opposite signs, perform addition
  759. if (this->sign == '+' and num.sign == '-') {
  760. BigInt rhs = num;
  761. rhs.sign = '+';
  762. return *this + rhs;
  763. }
  764. else if (this->sign == '-' and num.sign == '+') {
  765. BigInt lhs = *this;
  766. lhs.sign = '+';
  767. return -(lhs + num);
  768. }
  769. BigInt result; // the resultant difference
  770. // identify the numbers as `larger` and `smaller`
  771. std::string larger, smaller;
  772. if (abs(*this) > abs(num)) {
  773. larger = this->value;
  774. smaller = num.value;
  775. if (this->sign == '-') // -larger - -smaller = -result
  776. result.sign = '-';
  777. }
  778. else {
  779. larger = num.value;
  780. smaller = this->value;
  781. if (num.sign == '+') // smaller - larger = -result
  782. result.sign = '-';
  783. }
  784. // pad the smaller number with zeroes
  785. add_leading_zeroes(smaller, larger.size() - smaller.size());
  786. result.value = ""; // the value is cleared as the digits will be appended
  787. short difference;
  788. long i, j;
  789. // subtract the two values
  790. for (i = larger.size() - 1; i >= 0; i--) {
  791. difference = larger[i] - smaller[i];
  792. if (difference < 0) {
  793. for (j = i - 1; j >= 0; j--) {
  794. if (larger[j] != '0') {
  795. larger[j]--; // borrow from the j-th digit
  796. break;
  797. }
  798. }
  799. j++;
  800. while (j != i) {
  801. larger[j] = '9'; // add the borrow and take away 1
  802. j++;
  803. }
  804. difference += 10; // add the borrow
  805. }
  806. result.value = std::to_string(difference) + result.value;
  807. }
  808. strip_leading_zeroes(result.value);
  809. // if the result is 0, set its sign as +
  810. if (result.value == "0")
  811. result.sign = '+';
  812. return result;
  813. }
  814. /*
  815. BigInt * BigInt
  816. ---------------
  817. Computes the product of two BigInts using Karatsuba's algorithm.
  818. The operand on the RHS of the product is `num`.
  819. */
  820. BigInt BigInt::operator*(const BigInt& num) const {
  821. if (*this == 0 or num == 0)
  822. return BigInt(0);
  823. if (*this == 1)
  824. return num;
  825. if (num == 1)
  826. return *this;
  827. BigInt product;
  828. if (abs(*this) <= FLOOR_SQRT_LLONG_MAX and abs(num) <= FLOOR_SQRT_LLONG_MAX)
  829. product = std::stoll(this->value) * std::stoll(num.value);
  830. else {
  831. // identify the numbers as `larger` and `smaller`
  832. std::string larger, smaller;
  833. std::tie(larger, smaller) = get_larger_and_smaller(this->value, num.value);
  834. size_t half_length = larger.size() / 2;
  835. auto half_length_ceil = (size_t) ceil(larger.size() / 2.0);
  836. BigInt num1_high, num1_low;
  837. num1_high = larger.substr(0, half_length);
  838. num1_low = larger.substr(half_length);
  839. BigInt num2_high, num2_low;
  840. num2_high = smaller.substr(0, half_length);
  841. num2_low = smaller.substr(half_length);
  842. strip_leading_zeroes(num1_high.value);
  843. strip_leading_zeroes(num1_low.value);
  844. strip_leading_zeroes(num2_high.value);
  845. strip_leading_zeroes(num2_low.value);
  846. BigInt prod_high, prod_mid, prod_low;
  847. prod_high = num1_high * num2_high;
  848. prod_low = num1_low * num2_low;
  849. prod_mid = (num1_high + num1_low) * (num2_high + num2_low)
  850. - prod_high - prod_low;
  851. add_trailing_zeroes(prod_high.value, 2 * half_length_ceil);
  852. add_trailing_zeroes(prod_mid.value, half_length_ceil);
  853. strip_leading_zeroes(prod_high.value);
  854. strip_leading_zeroes(prod_mid.value);
  855. strip_leading_zeroes(prod_low.value);
  856. product = prod_high + prod_mid + prod_low;
  857. }
  858. strip_leading_zeroes(product.value);
  859. if (this->sign == num.sign)
  860. product.sign = '+';
  861. else
  862. product.sign = '-';
  863. return product;
  864. }
  865. /*
  866. divide
  867. ------
  868. Helper function that returns the quotient and remainder on dividing the
  869. dividend by the divisor, when the divisor is 1 to 10 times the dividend.
  870. */
  871. std::tuple<BigInt, BigInt> divide(const BigInt& dividend, const BigInt& divisor) {
  872. BigInt quotient, remainder, temp;
  873. temp = divisor;
  874. quotient = 1;
  875. while (temp < dividend) {
  876. quotient++;
  877. temp += divisor;
  878. }
  879. if (temp > dividend) {
  880. quotient--;
  881. remainder = dividend - (temp - divisor);
  882. }
  883. return std::make_tuple(quotient, remainder);
  884. }
  885. /*
  886. BigInt / BigInt
  887. ---------------
  888. Computes the quotient of two BigInts using the long-division method.
  889. The operand on the RHS of the division (the divisor) is `num`.
  890. */
  891. BigInt BigInt::operator/(const BigInt& num) const {
  892. BigInt abs_dividend = abs(*this);
  893. BigInt abs_divisor = abs(num);
  894. if (num == 0)
  895. throw std::logic_error("Attempted division by zero");
  896. if (abs_dividend < abs_divisor)
  897. return BigInt(0);
  898. if (num == 1)
  899. return *this;
  900. if (num == -1)
  901. return -(*this);
  902. BigInt quotient;
  903. if (abs_dividend <= LLONG_MAX and abs_divisor <= LLONG_MAX)
  904. quotient = std::stoll(abs_dividend.value) / std::stoll(abs_divisor.value);
  905. else if (abs_dividend == abs_divisor)
  906. quotient = 1;
  907. else {
  908. quotient.value = ""; // the value is cleared as digits will be appended
  909. BigInt chunk, chunk_quotient, chunk_remainder;
  910. size_t chunk_index = 0;
  911. chunk_remainder.value = abs_dividend.value.substr(chunk_index, abs_divisor.value.size() - 1);
  912. chunk_index = abs_divisor.value.size() - 1;
  913. while (chunk_index < abs_dividend.value.size()) {
  914. chunk.value = chunk_remainder.value.append(1, abs_dividend.value[chunk_index]);
  915. chunk_index++;
  916. while (chunk < abs_divisor) {
  917. quotient.value += "0";
  918. if (chunk_index < abs_dividend.value.size()) {
  919. chunk.value.append(1, abs_dividend.value[chunk_index]);
  920. chunk_index++;
  921. }
  922. else
  923. break;
  924. }
  925. if (chunk == abs_divisor) {
  926. quotient.value += "1";
  927. chunk_remainder = 0;
  928. }
  929. else if (chunk > abs_divisor) {
  930. strip_leading_zeroes(chunk.value);
  931. std::tie(chunk_quotient, chunk_remainder) = divide(chunk, abs_divisor);
  932. quotient.value += chunk_quotient.value;
  933. }
  934. }
  935. }
  936. strip_leading_zeroes(quotient.value);
  937. if (this->sign == num.sign)
  938. quotient.sign = '+';
  939. else
  940. quotient.sign = '-';
  941. return quotient;
  942. }
  943. /*
  944. BigInt % BigInt
  945. ---------------
  946. Computes the modulo (remainder on division) of two BigInts.
  947. The operand on the RHS of the modulo (the divisor) is `num`.
  948. */
  949. BigInt BigInt::operator%(const BigInt& num) const {
  950. BigInt abs_dividend = abs(*this);
  951. BigInt abs_divisor = abs(num);
  952. if (abs_divisor == 0)
  953. throw std::logic_error("Attempted division by zero");
  954. if (abs_divisor == 1 or abs_divisor == abs_dividend)
  955. return BigInt(0);
  956. BigInt remainder;
  957. if (abs_dividend <= LLONG_MAX and abs_divisor <= LLONG_MAX)
  958. remainder = std::stoll(abs_dividend.value) % std::stoll(abs_divisor.value);
  959. else if (abs_dividend < abs_divisor)
  960. remainder = abs_dividend;
  961. else {
  962. BigInt quotient = abs_dividend / abs_divisor;
  963. remainder = abs_dividend - quotient * abs_divisor;
  964. }
  965. strip_leading_zeroes(remainder.value);
  966. // remainder has the same sign as that of the dividend
  967. remainder.sign = this->sign;
  968. if (remainder.value == "0") // except if its zero
  969. remainder.sign = '+';
  970. return remainder;
  971. }
  972. /*
  973. BigInt + Integer
  974. ----------------
  975. */
  976. BigInt BigInt::operator+(const long long& num) const {
  977. return *this + BigInt(num);
  978. }
  979. /*
  980. Integer + BigInt
  981. ----------------
  982. */
  983. BigInt operator+(const long long& lhs, const BigInt& rhs) {
  984. return BigInt(lhs) + rhs;
  985. }
  986. /*
  987. BigInt - Integer
  988. ----------------
  989. */
  990. BigInt BigInt::operator-(const long long& num) const {
  991. return *this - BigInt(num);
  992. }
  993. /*
  994. Integer - BigInt
  995. ----------------
  996. */
  997. BigInt operator-(const long long& lhs, const BigInt& rhs) {
  998. return BigInt(lhs) - rhs;
  999. }
  1000. /*
  1001. BigInt * Integer
  1002. ----------------
  1003. */
  1004. BigInt BigInt::operator*(const long long& num) const {
  1005. return *this * BigInt(num);
  1006. }
  1007. /*
  1008. Integer * BigInt
  1009. ----------------
  1010. */
  1011. BigInt operator*(const long long& lhs, const BigInt& rhs) {
  1012. return BigInt(lhs) * rhs;
  1013. }
  1014. /*
  1015. BigInt / Integer
  1016. ----------------
  1017. */
  1018. BigInt BigInt::operator/(const long long& num) const {
  1019. return *this / BigInt(num);
  1020. }
  1021. /*
  1022. Integer / BigInt
  1023. ----------------
  1024. */
  1025. BigInt operator/(const long long& lhs, const BigInt& rhs) {
  1026. return BigInt(lhs) / rhs;
  1027. }
  1028. /*
  1029. BigInt % Integer
  1030. ----------------
  1031. */
  1032. BigInt BigInt::operator%(const long long& num) const {
  1033. return *this % BigInt(num);
  1034. }
  1035. /*
  1036. Integer % BigInt
  1037. ----------------
  1038. */
  1039. BigInt operator%(const long long& lhs, const BigInt& rhs) {
  1040. return BigInt(lhs) % rhs;
  1041. }
  1042. /*
  1043. BigInt + String
  1044. ---------------
  1045. */
  1046. BigInt BigInt::operator+(const std::string& num) const {
  1047. return *this + BigInt(num);
  1048. }
  1049. /*
  1050. String + BigInt
  1051. ---------------
  1052. */
  1053. BigInt operator+(const std::string& lhs, const BigInt& rhs) {
  1054. return BigInt(lhs) + rhs;
  1055. }
  1056. /*
  1057. BigInt - String
  1058. ---------------
  1059. */
  1060. BigInt BigInt::operator-(const std::string& num) const {
  1061. return *this - BigInt(num);
  1062. }
  1063. /*
  1064. String - BigInt
  1065. ---------------
  1066. */
  1067. BigInt operator-(const std::string& lhs, const BigInt& rhs) {
  1068. return BigInt(lhs) - rhs;
  1069. }
  1070. /*
  1071. BigInt * String
  1072. ---------------
  1073. */
  1074. BigInt BigInt::operator*(const std::string& num) const {
  1075. return *this * BigInt(num);
  1076. }
  1077. /*
  1078. String * BigInt
  1079. ---------------
  1080. */
  1081. BigInt operator*(const std::string& lhs, const BigInt& rhs) {
  1082. return BigInt(lhs) * rhs;
  1083. }
  1084. /*
  1085. BigInt / String
  1086. ---------------
  1087. */
  1088. BigInt BigInt::operator/(const std::string& num) const {
  1089. return *this / BigInt(num);
  1090. }
  1091. /*
  1092. String / BigInt
  1093. ---------------
  1094. */
  1095. BigInt operator/(const std::string& lhs, const BigInt& rhs) {
  1096. return BigInt(lhs) / rhs;
  1097. }
  1098. /*
  1099. BigInt % String
  1100. ---------------
  1101. */
  1102. BigInt BigInt::operator%(const std::string& num) const {
  1103. return *this % BigInt(num);
  1104. }
  1105. /*
  1106. String % BigInt
  1107. ---------------
  1108. */
  1109. BigInt operator%(const std::string& lhs, const BigInt& rhs) {
  1110. return BigInt(lhs) % rhs;
  1111. }
  1112. #endif // BIG_INT_BINARY_ARITHMETIC_OPERATORS_HPP
  1113. /*
  1114. ===========================================================================
  1115. Arithmetic-assignment operators
  1116. ===========================================================================
  1117. */
  1118. #ifndef BIG_INT_ARITHMETIC_ASSIGNMENT_OPERATORS_HPP
  1119. #define BIG_INT_ARITHMETIC_ASSIGNMENT_OPERATORS_HPP
  1120. /*
  1121. BigInt += BigInt
  1122. ----------------
  1123. */
  1124. BigInt& BigInt::operator+=(const BigInt& num) {
  1125. *this = *this + num;
  1126. return *this;
  1127. }
  1128. /*
  1129. BigInt -= BigInt
  1130. ----------------
  1131. */
  1132. BigInt& BigInt::operator-=(const BigInt& num) {
  1133. *this = *this - num;
  1134. return *this;
  1135. }
  1136. /*
  1137. BigInt *= BigInt
  1138. ----------------
  1139. */
  1140. BigInt& BigInt::operator*=(const BigInt& num) {
  1141. *this = *this * num;
  1142. return *this;
  1143. }
  1144. /*
  1145. BigInt /= BigInt
  1146. ----------------
  1147. */
  1148. BigInt& BigInt::operator/=(const BigInt& num) {
  1149. *this = *this / num;
  1150. return *this;
  1151. }
  1152. /*
  1153. BigInt %= BigInt
  1154. ----------------
  1155. */
  1156. BigInt& BigInt::operator%=(const BigInt& num) {
  1157. *this = *this % num;
  1158. return *this;
  1159. }
  1160. /*
  1161. BigInt += Integer
  1162. -----------------
  1163. */
  1164. BigInt& BigInt::operator+=(const long long& num) {
  1165. *this = *this + BigInt(num);
  1166. return *this;
  1167. }
  1168. /*
  1169. BigInt -= Integer
  1170. -----------------
  1171. */
  1172. BigInt& BigInt::operator-=(const long long& num) {
  1173. *this = *this - BigInt(num);
  1174. return *this;
  1175. }
  1176. /*
  1177. BigInt *= Integer
  1178. -----------------
  1179. */
  1180. BigInt& BigInt::operator*=(const long long& num) {
  1181. *this = *this * BigInt(num);
  1182. return *this;
  1183. }
  1184. /*
  1185. BigInt /= Integer
  1186. -----------------
  1187. */
  1188. BigInt& BigInt::operator/=(const long long& num) {
  1189. *this = *this / BigInt(num);
  1190. return *this;
  1191. }
  1192. /*
  1193. BigInt %= Integer
  1194. -----------------
  1195. */
  1196. BigInt& BigInt::operator%=(const long long& num) {
  1197. *this = *this % BigInt(num);
  1198. return *this;
  1199. }
  1200. /*
  1201. BigInt += String
  1202. ----------------
  1203. */
  1204. BigInt& BigInt::operator+=(const std::string& num) {
  1205. *this = *this + BigInt(num);
  1206. return *this;
  1207. }
  1208. /*
  1209. BigInt -= String
  1210. ----------------
  1211. */
  1212. BigInt& BigInt::operator-=(const std::string& num) {
  1213. *this = *this - BigInt(num);
  1214. return *this;
  1215. }
  1216. /*
  1217. BigInt *= String
  1218. ----------------
  1219. */
  1220. BigInt& BigInt::operator*=(const std::string& num) {
  1221. *this = *this * BigInt(num);
  1222. return *this;
  1223. }
  1224. /*
  1225. BigInt /= String
  1226. ----------------
  1227. */
  1228. BigInt& BigInt::operator/=(const std::string& num) {
  1229. *this = *this / BigInt(num);
  1230. return *this;
  1231. }
  1232. /*
  1233. BigInt %= String
  1234. ----------------
  1235. */
  1236. BigInt& BigInt::operator%=(const std::string& num) {
  1237. *this = *this % BigInt(num);
  1238. return *this;
  1239. }
  1240. #endif // BIG_INT_ARITHMETIC_ASSIGNMENT_OPERATORS_HPP
  1241. /*
  1242. ===========================================================================
  1243. Increment and decrement operators
  1244. ===========================================================================
  1245. */
  1246. #ifndef BIG_INT_INCREMENT_DECREMENT_OPERATORS_HPP
  1247. #define BIG_INT_INCREMENT_DECREMENT_OPERATORS_HPP
  1248. /*
  1249. Pre-increment
  1250. -------------
  1251. ++BigInt
  1252. */
  1253. BigInt& BigInt::operator++() {
  1254. *this += 1;
  1255. return *this;
  1256. }
  1257. /*
  1258. Pre-decrement
  1259. -------------
  1260. --BigInt
  1261. */
  1262. BigInt& BigInt::operator--() {
  1263. *this -= 1;
  1264. return *this;
  1265. }
  1266. /*
  1267. Post-increment
  1268. --------------
  1269. BigInt++
  1270. */
  1271. BigInt BigInt::operator++(int) {
  1272. BigInt temp = *this;
  1273. *this += 1;
  1274. return temp;
  1275. }
  1276. /*
  1277. Post-decrement
  1278. --------------
  1279. BigInt--
  1280. */
  1281. BigInt BigInt::operator--(int) {
  1282. BigInt temp = *this;
  1283. *this -= 1;
  1284. return temp;
  1285. }
  1286. #endif // BIG_INT_INCREMENT_DECREMENT_OPERATORS_HPP
  1287. /*
  1288. ===========================================================================
  1289. I/O stream operators
  1290. ===========================================================================
  1291. */
  1292. #ifndef BIG_INT_IO_STREAM_OPERATORS_HPP
  1293. #define BIG_INT_IO_STREAM_OPERATORS_HPP
  1294. /*
  1295. BigInt from input stream
  1296. ------------------------
  1297. */
  1298. std::istream& operator>>(std::istream& in, BigInt& num) {
  1299. std::string input;
  1300. in >> input;
  1301. num = BigInt(input); // remove sign from value and set sign, if exists
  1302. return in;
  1303. }
  1304. /*
  1305. BigInt to output stream
  1306. -----------------------
  1307. */
  1308. std::ostream& operator<<(std::ostream& out, const BigInt& num) {
  1309. if (num.sign == '-')
  1310. out << num.sign;
  1311. out << num.value;
  1312. return out;
  1313. }
  1314. #endif // BIG_INT_IO_STREAM_OPERATORS_HPP