I'm writing my own bignum class for operating on large numbers. So far I've overloaded the operator=
and operator+
. How do I perform long division?
Also, right now I can only assign values within the range of integers to the bignum object. How do I assign values that fall outside the int range? Is it possible to do this without strings?
#include <iostream>
using namespace std;
class bignum
{
public:
int number[20];
bignum operator + (bignum);
bignum operator = (int);
void output()
};
bignum bignum::operator= (int j)
{
int f;
f=j;
for(int k=0; k<=19; k++)
{
number[k]=0;
}
for(int l=19; l>=0,f>0; l--)
{
number[l]=(f%10);
f/=10;
}
}
bignu开发者_高级运维m bignum::operator+ (bignum b)
{
bignum a;
int carry=0;
for(int k=0; k<=19; k++)
{
a.number[k]=0;
}
for(int i=19; i>=0; i--)
{
a.number[i]= number[i]+b.number[i]+a.number[i];
if(a.number[i]>9)
{
carry=(a.number[i]/10);
a.number[i-1]+=carry;
a.number[i]=(a.number[i]%10);
}
}
return a;
}
int main()
{
bignum a,b,c;
a=9999;
b=a+a;
//for(int k=1; k<=9; k++)
//b.number[k]=0;
//b=a+a;
for(int k=0; k<=19; k++)
cout<<b.number[k];
cin.get();
}
For assigning big numbers the usual way is strings. This usually only happens at the interface to your calculations and so is not a problem. Another way would be to have a template constructor that takes a range of chars that you interpret as a Two's Compliment number (I prefer this method, but I havent seen it used very often).
If you are serious about implementing a BigNum class then I would suggest that you read up about Expression Templates as a way to reduce the cost of temporaries in natural looking code.
精彩评论