C ++ - 无符号整数的模数

时间:2014-07-14 21:07:52

标签: c++ c unsigned modulo bignum

工作解决方案(以防任何人这样做或类似的事情:P) 这不是最优化的解决方案,但它确实适用于32位我会发布一个更优化的解决方案,对每个值使用bigNum而不是unsigned int,因为谁知道你的值可能是(2 ^ 128)* (2 ^ 32):P

void print(){
    //Hold temporary backwards string array
    std::string backwards;
    //Copy of data and remainder to hold previous loop's value
    unsigned int topCopy = topValue, remainder = 0;
    //Loop through each digit of highest 32 bit number
    for(int i = 0; topCopy != 0; i++){
        //Find value of all added max values
        unsigned int value = maxValues*maxDigits[i];
        //Find value of topValue's last digit
        value += topCopy % 10;
        //Add in the remainder from the previous loop
        value += remainder;
        //Create remainder so the printing value is correct
        remainder = value / 10;
        //append the value to the string
        backwards += value % 10;
        //setup for the next digit
        topCopy /= 10;
    }
    //append the last digit
    backwards += remainder;
    //print backwards
    for(int i = backwards.length()-1; i >= 0; i--){
        printf("%i", backwards[i]);
    }
    printf("\n");
}

我正在尝试创建一个在C ++中处理任意长度无符号整数值的类,在有人说之前,我完全清楚已经存在已经存在的库来处理这个功能。这对我来说纯粹是一种学习经历。

实施说明:

我将以这种格式存储我的课程中的值:

topValue: stores the remainder of the number % 4294967296  
maxValues: stores how many max values are needed to hold the number  

示例:

maxValues = 4  
topValue = 2820130816  
maxValues *= 4294967296
maxValues == 17179869184
maxValues + topValue == 20000000000  

问题:

当我尝试打印数字时出现问题,我已经实现了加法减法等方法...当我为这个数字的每个数字决定要打印的内容时我会这样做:

  1. 从结束(6)4294967296
  2. 开始比较数字
  3. 将此添加到topValue%10(topValue的结束编号)
  4. 打印值并将剩余的topValue除以10得到下一个值

    const char maxDigits[] = {6, 9, 2, 7, 6, 9, 4, 9, 2, 4};
    void print(){
        int topCopy = topValue;
        for(int i = 0; topCopy != 0; i++){
            int value = maxValues*maxDigits[i];
            value += topCopy % 10; // RIGHT HERE IS THE ISSUE
            value %= 10;
            //print value
            topCopy /= 10;
        }
    
    }
    
  5. 当对这个无符号值执行行topCopy % 10时,它会给出答案,就像它是一个有符号的值,并给出一个不正确的否定答案,我需要的是可以提取无符号值的最后一位数的东西

    2,820,130,816 10 应该(对我来说) 6 但输出 0

    TL; DR:

    我需要一个操作,从 2,820,130,816 10 而不是0来给我6个。

    谢谢!

2 个答案:

答案 0 :(得分:4)

模运算的结果取决于操作数的类型。由于您的第一个操作数是int,并且因为2,820,130,816大于可以存储在32位int中的最大值,所以会得到错误的结果。

topCopy的类型更改为unsigned可以解决此问题,并返回6。

Demo on ideone.

答案 1 :(得分:0)

由于您正在处理一些大数字,因此您可能希望使用更大的整数类型,例如unsigned long long。你溢出了32位int的范围。

相关问题