c++ 中的 Bignum 除法和赋值
我正在编写自己的 bignum 类来对大数进行操作。到目前为止,我已经重载了 operator=
和 operator+
。如何进行长除法?
另外,现在我只能将整数范围内的值分配给 bignum 对象。如何分配 int 范围之外的值?没有字符串可以做到这一点吗?
#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;
}
}
bignum 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();
}
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;
}
}
bignum 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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于分配大数字,通常的方法是字符串。这通常只发生在计算的接口处,因此不是问题。另一种方法是使用一个模板构造函数,它接受一系列字符,您将其解释为“二的恭维数字”(我更喜欢这种方法,但我还没有看到它经常使用)。
如果您真的想实现 BigNum 类,那么我建议您阅读有关表达式模板的内容,以此作为减少自然代码中临时变量成本的方法。
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.