2 * Sample program demonstrating the most important features of the Big
10 // For the BigInteger class itself.
11 #include "BigInteger.hh"
13 // For the 4 routines `easy BI/BU <=> string' and `iostream' integration.
14 #include "BigIntegerUtils.hh"
18 BigInteger a; // a is 0
21 a = b; // From int to BigInteger implicitly...
22 b = a.toInt(); // ...and back explicitly.
24 * If a were too big for an int you'd get a runtime exception.
25 * The Big Integer Library throws C-strings (that is,
26 * `const char *'s) when something goes wrong. It's a good idea
27 * to catch them; the `try/catch' construct wrapping all this
28 * code is an example of how to do this. Some C++ compilers need
29 * a special command-line option to compile code that uses
33 BigInteger c(a); // Copy a BigInteger.
35 // d is -314159265. The `int' literal is converted to a
37 BigInteger d(-314159265);
39 // This won't compile because the number is too big to be an
41 //BigInteger e(3141592653589793238462643383279);
43 // Instead you can convert the number from a string.
44 std::string s("3141592653589793238462643383279");
45 BigInteger f = easyStringToBI(s);
47 // You can convert the other way too.
48 std::string s2 = easyBItoString(f);
50 // f is stringified and send to std::cout.
51 std::cout << f << std::endl;
56 * The Big Integer Library provides lots of overloaded operators
57 * and corresponding assignment operators. So you can do `a + b'
58 * with BigIntegers just as with normal integers. The named
59 * methods `add', `divideWithRemainder', etc. are more advanced
60 * ``put-here operations''; see `BigUnsigned.hh' for details.
62 BigInteger g(314159), h(265);
63 // All five ``return-by-value'' arithmetic operators.
64 std::cout << (g + h) << '\n' << (g - h) << '\n' << (g * h)
65 << '\n' << (g / h) << '\n' << (g % h) << std::endl;
67 BigUnsigned i(0xFF0000FF), j(0x0000FFFF);
68 // All five ``return-by-value'' bitwise operators.
69 std::cout.flags(std::ios::hex | std::ios::showbase);
70 std::cout << (i & j) << '\n' << (i | j) << '\n' << (i ^ j) << '\n'
71 << (j << 21) << '\n' << (j >> 10) << '\n';
72 std::cout.flags(std::ios::dec);
74 // Let's do some heavy lifting and calculate powers of 314.
76 BigUnsigned x(1), big314(314);
77 for (int power = 0; power <= maxPower; power++) {
78 std::cout << "314^" << power << " = " << x << std::endl;
79 x *= big314; // A BigInteger assignment operator
83 * If you want to experiment with the library,
84 * you can add your own test code here.
86 // std::cout << "Beginning of custom test code:" << std::endl;
88 } catch(char const* err) {
89 std::cout << "The library threw an exception:\n"
97 Running the sample program produces this output:
99 3141592653589793238462643383279
115 314^5 = 3052447761824
116 314^6 = 958468597212736
117 314^7 = 300959139524799104
118 314^8 = 94501169810786918656
119 314^9 = 29673367320587092457984
120 314^10 = 9317437338664347031806976