I made a bigint class that can add unsigned unlimited precision integers by splitting number into chunks less than 9999, and if a part is bigger than 9999 I take mod 10000 and carry 1 to the next part.
The adding function looks a bit messy as I had to make adjustments for the algorithm if rhs has more/less digits than lhs. Is there a way to make this programm more compact and readable?
class bigint { std::vector<int> parts; public: bigint(unsigned long long n); friend std::ostream& operator<<(std::ostream& os, const bigint& n); bigint& operator+=(bigint n); }; bigint::bigint(unsigned long long n) { while(n != 0) { parts.push_back(n%10000); n/=10000; } } std::ostream& operator<<(std::ostream& os, const bigint& n) { for(auto it = n.parts.rbegin(); it != n.parts.rend(); ++it)os << (*it); return os; } bigint& bigint::operator+=(bigint n) { auto a = parts.begin(), b = n.parts.begin(); int carry = 0; while(a != parts.end() && b != n.parts.end()) { *a+=*b+carry; carry = 0; if(*a > 9999) { *a = *a%10000; carry = 1; } ++a; ++b; } // If rhs has more digits than lhs if(a == parts.end() && b != n.parts.end()) { while(b != n.parts.end()) { parts.push_back(0); a = --parts.end(); *a+=*b+carry; carry = 0; if(*a > 9999) { *a = *a%10000; carry = 1; } ++a; ++b; } } // If lhs has more digits than rhs if(b == n.parts.end() && a != parts.end()) { while(a != n.parts.end() && carry == 1) { *a+=carry; carry = 0; if(*a > 9999) { *a = *a%10000; carry = 1; } ++a; } } if(carry == 1)parts.push_back(1); return *this; }
bigintclass. Perhaps you could post at least a minimal set of missing features? \$\endgroup\$