实现大数四则运算
发布时间:2021-05-27 11:27:52 所属栏目:大数据 来源:网络整理
导读:副标题#e# ? ? ? ? 由于编程语言提供的基本数值数据类型表示的数值范围有限,不能满足较大规模的高精度数值计算,因此需要利用其他方法实现高精度数值的计算,于是产生了大数运算。大数运算主要有加、减、乘三种方法。那么大数到底如何进行运算呢,学习过数
|
大数的除法运算: BigData?BigData::operator/(const?BigData&?bigdata)
{
//1、除数为0
if?(bigdata._strData[1]?==?'0')
{
assert(false);
}
//2、两个数没溢出
if?(IsINT64OverFlow()?&&?bigdata.IsINT64OverFlow())
{
return?_value?/?bigdata._value;
}
//3、除数为1或-1
if?(bigdata._value?==?1?||?bigdata._value?==?-1)
{
return?_value;
}
//4、除数和被除数相等
//if?(strcmp(_strData.data()?+?1,?bigdata._strData.data()?+?1)?==?0)
//data()返回内容的字符数组形式
if?(strcmp(_strData.c_str()?+?1,?bigdata._strData.c_str()?+?1)?==?0)
{
if?(_strData[0]?!=?bigdata._strData[0])
{
return?BigData(INT64(-1));
}
return?BigData(INT64(1));
}
if?(_strData.size()?<?bigdata._strData.size()?||
_strData.size()?==?bigdata._strData.size()?&&
strcmp(_strData.c_str()?+?1,?bigdata._strData.c_str()?+?1)?<?0)
{
return?BigData(INT64(0));
}
return?BigData(Div(_strData,?bigdata._strData).c_str());
}
std::string?BigData::Div(std::string?left,?std::string?right)
{//此处用append()对字符串依次赋值
std::string?sRet;
sRet.append(1,?'+');
if?(left[0]?!=?right[0])
{
sRet[0]?=?'-';
}
char*?pLeft?=?(char*)left.c_str()?+?1;
char*?pRight?=?(char*)right.c_str()?+?1;
int?DataLen?=?right.size()?-?1;//标记相除的除数位数
int?Lsize?=?left.size()?-?1;
int?Rsize?=?right.size()?-?1;
//eg:222222/33首先取到22和33比较大小,如果大就直接相除,否则DataLen++;
for?(int?iIdx?=?0;?iIdx?<?Lsize;)
{
if?(!(IsLeftstrBig(pLeft,?DataLen,?pRight,?Rsize)))//如果取到的数小于除数时,结果商0,向后再取一位
{
sRet.append(1,?'0');
DataLen++;
}
else
{
sRet.append(1,?SubLoop(pLeft,?Rsize));//循环相减得到该位的商
//判断pLeft中进行循环相减后依次去掉0,
while?(*pLeft?==?'0'?&&?DataLen?>?0)
{
pLeft++;
DataLen--;
iIdx++;
}
DataLen++;
}
if?(DataLen?>?Rsize?+?1)//pLeft比pRight大一位结果为0,则pLeft中含有0
{
pLeft++;
DataLen--;
iIdx++;
}
if?(DataLen?+?iIdx?>?Lsize)//判断是否除法结束
break;
}
return?sRet;
}?
char?BigData::SubLoop(char*?pLeft,?int?Rsize)
{
assert(pLeft?&&?pRight);
char?cRet?=?0;
while?(IsLeftstrBig(pLeft,?Lsize,?Rsize))//直到被减数小于减数停止运算
{
for?(int?iIdx?=?0;?iIdx?<?Rsize;?iIdx++)//进行减运算
{
char?ret?=?pLeft[Lsize?-?iIdx?-?1]?-?'0';
ret?-=?pRight[Rsize?-?iIdx?-?1]?-?'0';
if?(ret?<?0)
{
pLeft[Lsize?-?iIdx?-?2]?-=?1;
ret?+=?10;
}
pLeft[Lsize?-?iIdx?-?1]?=?ret?+?'0';
}
while?(*pLeft?==?'0'&&Lsize>0)
{
pLeft++;
Lsize--;
}
cRet++;
}
return?cRet?+?'0';
}
bool?BigData::IsLeftstrBig(const?char*?pLeft,?int?Rsize)//判断是否left大于right
{
assert(pLeft?&&?pRight);
char*?pleft?=?(char*)pLeft;
char*?pright?=?(char*)pRight;
if?(Lsize?>?Rsize?&&?*pleft?>?'0')//eg:112和33
{
return?true;
}
else?if?(Lsize?==?Rsize)//eg:57和33
{
while?(pright)
{
if?(*pleft?>?*pright)
{
return?true;
}
else?if?(*pleft?==?*pright)
{
pleft++;
pright++;
}
else
return?false;
}
}
return?false;
}
(编辑:娄底站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |


