1 // Sample program demonstrating the use of the Big Integer Library.
7 // `BigIntegerLibrary.hh' includes all of the library headers.
8 #include "BigIntegerLibrary.hh"
11 /* The library throws `const char *' error messages when things go
12 * wrong. It's a good idea to catch them using a `try' block like this
13 * one. Your C++ compiler might need a command-line option to compile
14 * code that uses exceptions. */
16 BigInteger a; // a is 0
19 /* Any primitive integer can be converted implicitly to a
23 /* The reverse conversion requires a method call (implicit
24 * conversions were previously supported but caused trouble).
25 * If a were too big for an int, the library would throw an
29 BigInteger c(a); // Copy a BigInteger.
31 // The int literal is converted to a BigInteger.
32 BigInteger d(-314159265);
34 /* This won't compile (at least on 32-bit machines) because the
35 * number is too big to be a primitive integer literal, and
36 * there's no such thing as a BigInteger literal. */
37 //BigInteger e(3141592653589793238462643383279);
39 // Instead you can convert the number from a string.
40 std::string s("3141592653589793238462643383279");
41 BigInteger f = stringToBigInteger(s);
43 // You can convert the other way too.
44 std::string s2 = bigIntegerToString(f);
46 // f is implicitly stringified and sent to std::cout.
47 std::cout << f << std::endl;
49 /* Let's do some math! The library overloads most of the
50 * mathematical operators (including assignment operators) to
51 * work on BigIntegers. There are also ``copy-less''
52 * operations; see `BigUnsigned.hh' for details. */
54 // Arithmetic operators
55 BigInteger g(314159), h(265);
56 std::cout << (g + h) << '\n'
60 << (g % h) << std::endl;
63 BigUnsigned i(0xFF0000FF), j(0x0000FFFF);
64 // The library's << operator recognizes base flags.
65 std::cout.flags(std::ios::hex | std::ios::showbase);
66 std::cout << (i & j) << '\n'
69 // Shift distances are ordinary unsigned ints.
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
82 // Some big-integer algorithms (albeit on small integers).
83 std::cout << gcd(BigUnsigned(60), 72) << '\n'
84 << modinv(BigUnsigned(7), 11) << '\n'
85 << modexp(BigUnsigned(314), 159, 2653) << std::endl;
87 // Add your own code here to experiment with the library.
88 } catch(char const* err) {
89 std::cout << "The library threw an exception:\n"
97 The original 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