Right now I have a snippet of code that makes logical sense but in fact doesn't work
Actually, that snippet makes no sense at all. If you're looking to write a bigint library, then your best bet would be to find a simple one and study the code. A good start is to implement the most basic arithmetic in the simplest manner possible. For example:
#include <algorithm>
#include <iostream>
#include <ostream>
#include <string>
namespace jsw {
class integer {
std::string _base;
public:
integer(const char *init = "0");
integer(const std::string& init = "0");
integer add(const integer& rhs);
friend std::ostream& operator<<(std::ostream& out, const integer& obj);
};
integer::integer(const char *init)
: _base(init)
{}
integer::integer(const std::string& init)
: _base(init)
{}
integer integer::add(const integer& rhs)
{
using std::string;
string::size_type x = _base.size() - 1;
string::size_type y = rhs._base.size() - 1;
int carry = 0;
string result;
// Add two digits while there are more
while (x < string::npos && y < string::npos) {
int sum = carry + (_base[x--] - '0') + (rhs._base[y--] - '0');
carry = sum / 10;
result.push_back(sum % 10 + '0');
}
// Fill in the rest
while (x < string::npos) {
int sum = carry + (_base[x--] - '0');
carry = sum / 10;
result.push_back(sum % 10 + '0');
}
while (y < string::npos) {
int sum = carry + (rhs._base[y--] - '0');
carry = sum / 10;
result.push_back(sum % 10 + '0');
}
// The result was built backward, fix it
std::reverse(result.begin(), result.end());
return integer(result);
}
std::ostream& operator<<(std::ostream& out, const integer& obj)
{
return out << obj._base;
}
}
int main()
{
jsw::integer a = "123", b = "456";
std::cout << a << " + " << b << " = " << a.add(b) << '\n';
} Writing a big number library isn't inherently difficult; making it efficient is where the real challenge lies, and that part can get pretty complex.
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401