I made a MegaInt class that could handle very large numbers and overloaded a few operators. Unfortunately I’ve gotten stuck and my code just crashes.
Each MegaInt ojb has a vector value and an bool sign. Each position of a number is placed in the vector (i.e. 4325 is vector value = {5,2,3,4}) and whether its sign (+ or -) is 1 or 0.
here’s a bit of the code…
#include <vector>
#include <string>
using namespace std;
class MegaInt{
friend class main;
private:
vector<int> value;
bool sign; //true is pos, false is neg
public:
MegaInt(vector <int> x, bool y);
MegaInt(string s);
MegaInt(const MegaInt& m);
MegaInt & operator*=(const MegaInt &rhs);
#include <iostream>
using namespace std;
#include "MegaInt.h"
#include <math.h>
MegaInt::MegaInt(string s){
int pos = s.length()-1;
while (pos >= 0){
if(pos == 0 && s[pos] == '-'){
sign = false;
break;
}
else if (pos == 0 && s[pos] == '+'){
sign = true;
break;
}
else{
sign = true;
}
if(s[pos] >= 48 && s[pos] <= 57)
value.push_back(s[pos]-48);
else{
value.clear();
break;
}
pos --;
}
chopoffleadingOs();
}
MegaInt::MegaInt(const MegaInt& m){
value = m.value;
sign = m.sign;
}
MegaInt operator*(const MegaInt& x, const MegaInt& y){
int multi = 0;
int temp;
vector<int> total;
for(int i = x.value.size()-1; i>=0; --i){
for(int j = y.value.size()-1, k = 0; j>=0; --j, ++k){
temp = x.value[i] * y.value[j];
if (total.size() <= (i + multi + 1))
total.resize(i + multi + 1 + 1);
total[i + multi] += (temp % 10);
temp = (temp - total[i]) / 10;
total[i + multi + 1] += temp;
}
multi++;
}
reverse(total.begin(), total.end());
return newTotal;
}
I mainly seem to be stuck on the overloaded multiplication part. The rest I think i got.
Thanks,
Noah
One likely the problem is here:
You use the
totalvector, but haven’t allocated memory for it. This can be done through theresizefunction:A good way to find unexpected crashes is to use the debugger. If you run the program in a debugger, it will halt when there is a problem so you can examine variables and see both where the crash is and what may have caused it.
Edit:
If you don’t know the size of the
totalvector beforehand, you have to resize it dynamically: