A comprehensive C++ library for handling arbitrarily large integers with full arithmetic operations support.
The BigInteger class provides a solution for working with integers that exceed the range of built-in C++ integer types. Unlike languages like Java or Python that have built-in support for big integers, C++ requires a custom implementation. This library fills that gap by providing a robust, efficient, and easy-to-use big integer class.
- ✅ Arbitrary Precision: Handle integers with thousands of digits
- ✅ Full Arithmetic Support: Addition, subtraction, multiplication, division, modulo
- ✅ Negative Numbers: Complete support for negative integers
- ✅ Comparison Operations: All standard comparison operators
- ✅ Stream I/O: Integration with
coutandcin - ✅ Power Function: Efficient exponentiation using binary exponentiation
- ✅ GCD Calculation: Greatest Common Divisor computation
- ✅ String Conversion: Easy conversion to/from strings
- ✅ Memory Efficient: Optimized storage using vectors
- ✅ Exception Safe: Proper error handling for edge cases
#include "BigInteger.h"
#include <iostream>
using namespace std;
int main() {
// Create big integers
BigInteger a("123456789012345678901234567890");
BigInteger b("987654321098765432109876543210");
// Basic arithmetic
cout << "a + b = " << a + b << endl;
cout << "a * b = " << a * b << endl;
// Power operation
BigInteger c("12345");
cout << "12345^10 = " << c.power(10) << endl;
return 0;
}// From integer
BigInteger num1(123456789);
// From string
BigInteger num2("999999999999999999999999999999");
// From negative string
BigInteger num3("-123456789012345678901234567890");
// Copy constructor
BigInteger num4(num2);
// Default constructor (creates 0)
BigInteger num5;| Constructor | Description |
|---|---|
BigInteger() |
Creates a BigInteger with value 0 |
BigInteger(long long num) |
Creates from a long long integer |
BigInteger(const string& str) |
Creates from string representation |
BigInteger(const BigInteger& other) |
Copy constructor |
| Operation | Operator | Description |
|---|---|---|
| Addition | +, += |
Add two BigIntegers |
| Subtraction | -, -= |
Subtract two BigIntegers |
| Multiplication | *, *= |
Multiply two BigIntegers |
| Division | /, /= |
Integer division |
| Modulo | %, %= |
Remainder after division |
| Unary Minus | - |
Negate the number |
| Unary Plus | + |
Return positive copy |
| Operator | Description |
|---|---|
== |
Equal to |
!= |
Not equal to |
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
| Function | Description |
|---|---|
toString() |
Convert to string representation |
isZero() |
Check if the number is zero |
isPositive() |
Check if the number is positive |
isNegativeValue() |
Check if the number is negative |
power(int exp) |
Raise to the power of exp |
gcd(const BigInteger& other) |
Calculate GCD with another BigInteger |
BigInteger num;
cin >> num; // Input from stream
cout << num; // Output to streamBigInteger a("123456789012345678901234567890");
BigInteger b("987654321098765432109876543210");
BigInteger sum = a + b;
BigInteger product = a * b;
BigInteger quotient = b / a;
BigInteger remainder = b % a;
cout << "Sum: " << sum << endl;
cout << "Product: " << product << endl;
cout << "Quotient: " << quotient << endl;
cout << "Remainder: " << remainder << endl;BigInteger positive("123456789");
BigInteger negative("-987654321");
BigInteger result1 = positive + negative; // -864197532
BigInteger result2 = positive * negative; // -121932631112635269
BigInteger result3 = -positive; // -123456789BigInteger base("12345");
BigInteger power_result = base.power(5); // 12345^5
BigInteger a("48");
BigInteger b("18");
BigInteger gcd_result = a.gcd(b); // 6BigInteger a("123456789");
BigInteger b("987654321");
if (a < b) {
cout << "a is smaller than b" << endl;
}
if (a != b) {
cout << "a and b are different" << endl;
}- Addition/Subtraction: O(n) where n is the number of digits
- Multiplication: O(n²) using standard multiplication algorithm
- Division: O(n²) using long division method
- Power: O(log exp) using binary exponentiation
- GCD: O(log min(a,b)) using Euclidean algorithm
The library uses a vector<int> to store digits, where each element stores a single decimal digit (0-9). Memory usage is approximately:
- 4 bytes per digit + vector overhead
- Automatic memory management through RAII
The library includes proper error handling for:
- Division by zero: Throws
runtime_error - Negative exponents: Throws
runtime_error - Invalid string input: Gracefully handles malformed input
g++ -std=c++11 -O2 main.cpp -o mainThe library requires C++11 or later for vector operations and proper exception handling.
- Precision: Integer operations only (no floating-point support)
- Negative exponents: Not supported in power function
- Base conversion: Only decimal base supported
- Threading: Not thread-safe (use external synchronization if needed)
Contributions are welcome! Areas for improvement:
- Faster multiplication algorithms (Karatsuba, FFT)
- Support for different number bases
- Thread safety
- More utility functions (factorial, prime checking, etc.)
This project is released under the MIT License. Feel free to use, modify, and distribute as needed.
Numbers are stored in a vector<int> with digits in reverse order (least significant digit first). This design choice optimizes arithmetic operations by allowing easy access to the least significant digits during carry operations.
A separate boolean flag isNegative tracks the sign, allowing clean separation of magnitude and sign operations.
- Leading zero removal: Automatic cleanup maintains canonical form
- Short-circuit evaluation: Zero detection optimizes many operations
- Efficient power computation: Binary exponentiation reduces complexity
- Memory pre-allocation: Reserves appropriate space for multiplication results
Built with ❤️ for the C++ community. Happy coding with big numbers!