2 * Matt McCutchen's Big Integer Library
4 * Sample program demonstrating the most important features of the Big
12 // For the BigInteger class itself.
13 #include "BigInteger.hh"
15 // For the 4 routines `easy BI/BU <=> string' and `iostream' integration.
16 #include "BigIntegerUtils.hh"
20 BigInteger a; // a is 0
23 a = b; // From int to BigInteger...
24 b = a; // ...and back, no casts required!
26 * If a were too big for an int you'd get a runtime exception.
27 * The Big Integer Library throws C-strings (that is,
28 * `const char *'s) when something goes wrong. It's a good idea
29 * to catch them; the `try/catch' construct wrapping all this
30 * code is an example of how to do this. Some C++ compilers need
31 * a special command-line option to compile code that uses
35 BigInteger c(a); // Copy a BigInteger.
37 // d is -314159265. The `int' literal is converted to a
39 BigInteger d(-314159265);
41 // This won't compile because the number is too big to be an
43 //BigInteger e(3141592653589793238462643383279);
45 // Instead you can convert the number from a string.
46 std::string s("3141592653589793238462643383279");
47 BigInteger f = easyStringToBI(s);
49 // You can convert the other way too.
50 std::string s2 = easyBItoString(f);
52 // f is stringified and send to std::cout.
53 std::cout << f << std::endl;
58 * The Big Integer Library provides lots of overloaded operators
59 * and corresponding assignment operators. So you can do `a + b'
60 * with BigIntegers just as with normal integers. The named
61 * methods `add', `divideWithRemainder', etc. are more advanced
62 * ``put-here operations''; see `BigUnsigned.hh' for details.
64 BigInteger g(314159), h(265);
65 // All five ``return-by-value'' operators.
66 std::cout << (g + h) << '\n' << (g - h) << '\n' << (g * h)
67 << '\n' << (g / h) << '\n' << (g % h) << std::endl;
69 // Let's do some heavy lifting and calculate powers of 314.
71 BigUnsigned x(1), big314(314);
72 for (int power = 0; power <= maxPower; power++) {
73 std::cout << "314^" << power << " = " << x << std::endl;
74 x *= big314; // A BigInteger assignment operator
78 * If you want to experiment with the library,
79 * you can add your own test code here.
81 // std::cout << "Beginning of custom test code:" << std::endl;
83 } catch(char const* err) {
84 std::cout << "The library threw an exception:\n"
92 Running the sample program produces this output:
94 3141592653589793238462643383279
105 314^5 = 3052447761824
106 314^6 = 958468597212736
107 314^7 = 300959139524799104
108 314^8 = 94501169810786918656
109 314^9 = 29673367320587092457984
110 314^10 = 9317437338664347031806976