这里我有一个bigint计算器,它使用safearray类(未显示)来存储大数字并对它们进行算术运算。我有加法和减法工作,但当我尝试乘法时,它编译并运行但没有任何反应。有人可以帮我解决这个问题吗?感谢
int size = 100;
class bigint
{
SafeArray<int> *arr;
public:
char sign;
bigint() //initializes to zero
{
arr = new SafeArray<int>;
for(int i =0;i < size; i++)
arr->set(i,0);
}
void print() //prints numbers without zeroes in front
{
bool start_num=false;
for(int i = 0;i <arr->get_size() ;i++)
{
if(arr->get(i)!=0 && start_num==false )
{start_num=true;
cout << arr->get(i);}
else if(start_num==true)
cout<<arr->get(i);
}
cout<<endl;
}
void assign(const bigint &A) //
{
for(int i=0;i<arr->get_size();i++)
{ //Ways to initialize stuff
arr->set(i,A.arr->get(i));
}
}
void assign(int num) //
{
for(int i = arr->get_size()- 1; i >= 0; i--)
{
arr->set(i,num%10);
num /=10;
}
}
void assign(string num) //
{
long len = num.length();
int j=arr->get_size()-1;
for(long i=len-1;i>=0;i--)
{
arr->set(j,num[i]-48);
j--;
}
}
void add_pos(const bigint &A) //add big ints
{
int carry=0;
for(int i=size-1;i>=0;i--)
{
int result = arr->get(i)+A.arr->get(i)+carry;
arr->set(i,result%10);
carry=result/10;
}
}
void multiply(bigint &A)
{
bigint temp;
for(int i=0;i<size;i +=1)
{
temp.arr->set(i,arr->get(i));
arr->set(i,0);
}
int i1, i2;
for(i2=0; i2<size; i2++)
{
int borrow =0;
for(i1=0;i1+i2<size;i1++)
{
int total=temp.arr->get(i1)*A.arr->get(i2);
int totalsum=total+arr->get(i1+i2)+borrow;
arr->set(i1+i2,totalsum%10);
borrow = totalsum/10;
}
}
};
int main()
{
bigint a, b, c;
a.assign("2543281");
b.assign("3434");
a.mulitply(b);
a.print();
return 0;
}
答案 0 :(得分:1)
两个bigint
个size = 100
个数相乘的结果肯定需要100
个数字,可能是200
?
对于最小修改,您可以将size
作为构造函数参数传递给bigint
。理想情况下,bigint
可以使用向量,以便数字数组可以方便灵活地动态增长。
class bigint {
std::vector<int8_t> digits_; // each digit must be in 0-9 range
...
答案 1 :(得分:-1)
这些都很复杂,所以我想到了:
InfInt InfInt::operator*(const InfInt& a) const{
InfInt final = 0;
std::string result;
InfInt* temp;
int carry;
int current;
//fast mult algorithm. the same we were taught in elementary.
for(long i=length() - 1;i >= 0; i--){
carry = 0;
result = "";
for (long j=a.length() - 1; j >= 0; j--){
current = (value[i] - '0') * (a.value[j] - '0') + carry;
result = (char)(current % 10 + '0') + result;
carry = current / 10;
}
if (carry > 0)
result = (char)(carry + '0') + result;
temp = new InfInt(result);
final += *new InfInt(temp->alignLeft(length() - i - 1));
}
final.setSign(sign ^ a.sign);
return final;
}
希望有帮助