// sample class for storing an integer with an arbitrary number of digits #include #include #include #include #include using namespace std; class big_integer { public: big_integer(int n = 0) { digits.push_back(n % 10); n /= 10; while (n != 0) { digits.push_back(n % 10); n /= 10; } } big_integer(string s) { for (int i = s.size() - 1; i >= 0; i--) { digits.push_back(s[i] - '0'); } } string to_string() const { ostringstream out; for (int i = digits.size() - 1; i >= 0; i--) { out << digits[i]; } return out.str(); } // pre : n < INT_MAX / 10 (to avoid integer overflow) big_integer & operator*=(int n) { if (n >= INT_MAX / 10) { throw runtime_error("int is too big"); } int carry = 0; for (int & digit : digits) { digit = digit * n + carry; carry = digit / 10; digit = digit % 10; } while (carry > 0) { digits.push_back(carry % 10); carry /= 10; } return *this; } private: vector digits; }; bool operator==(const big_integer & lhs, const big_integer & rhs) { return lhs.to_string() == rhs.to_string(); } bool operator!=(const big_integer & lhs, const big_integer & rhs) { return !(lhs == rhs); } ostream & operator<<(ostream & out, const big_integer & big) { out << big.to_string(); return out; } istream & operator>>(istream & in, big_integer & big) { string s; in >> s; big = big_integer(s); return in; } int main() { big_integer x(1234); big_integer y(49); big_integer z("657894365382796543289"); big_integer a("1234"); cout << "give me a big int: "; big_integer b; cin >> b; cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "z = " << z << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << endl; cout << "x == y returns " << (x == y) << endl; cout << "x == a returns " << (x == a) << endl; cout << "x == x returns " << (x == x) << endl; cout << "x == z returns " << (x == z) << endl; cout << "x == 1234 returns " << (x == 1234) << endl; cout << "1234 == x returns " << (1234 == x) << endl; cout << endl; big_integer fact(1); for (int i = 1; i <= 30; i++) { fact *= i; cout << i << "! = " << fact << endl; } cout << endl; return 0; }