繁体   English   中英

无整数添加整数

[英]Adding Integers without longs

我正在写一个模型来模拟大整数。 我将数据作为无符号整数存储在称为数据的矢量指针中。 此函数的作用是将n添加到当前的大整数。 似乎在减慢我的表现的是必须使用长的long值。 你们中的任何人是否知道解决此问题的方法。 我目前必须使总和很长一段时间,否则它将溢出。

void Integer::u_add(const Integer & n)
{
    std::vector<unsigned int> & tRef = *data;
    std::vector<unsigned int> & nRef = *n.data;
    const int thisSize = tRef.size();
    const int nSize = nRef.size();
    int carry = 0;
    for(int i = 0; i < nSize || carry; ++i)
    {
        bool readThis = i < thisSize;
        long long sum = (readThis ? (long long)tRef[i] + carry : (long long)carry) + (i < nSize ? nRef[i] : 0);
        if(readThis)
            tRef[i] = sum % BASE; //Base is 2^32
        else
            tRef.push_back(sum % BASE);
        carry = (sum >= BASE ? 1 : 0);
    }
}

还只是想知道使用指针引用比仅使用指针本身有什么好处吗? 我的意思是我应该使用tRef [i]或(* data)[i]来访问数据。

代替使用2 ^ 32的底数,而使用2 ^ 30的底数。 然后,当您将两个值相加时,最大的和为2 ^ 31-1,适合普通的long (有符号或无符号)。

或更妙的是,使用基数10 ^ 9(大约等于2 ^ 30),则无需花费很多精力即可将大数以十进制格式打印。


如果您确实需要在2 ^ 32的基数上工作,则可以尝试以下操作,只要unsigned int不会引发溢出异常即可:

sum = term1 + term2
carry = 0
if (sum < term1 || sum < term2)
    carry = 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM