添加模数128位数

时间:2017-11-04 12:39:33

标签: arrays math addition subtraction

我有两个128位的数字。让它成为相同的数字:

A=282434364544378924672110924168367615433
B=282434364544378924672110924168367615433

有必要添加模数

340282366920938463460374607431768211337

为了表示128位数字,我使用了两个64位数组

low_A = A.aa[0];
low_B = B.aa[0];
low_M = M.aa[0];
high_A = A.aa[1];
high_B = B.aa[1];
high_M = M.aa[1];

因此,选择下部和上部(我们可以粗略地说,以这种方式将数字呈现给第64个数字系统)。 问题是当添加数字A和B时,物理上发生溢出。虽然二进制表示保持为真,但是对不存在的位执行传输。如果有转移,我们当然已经知道给定数量大于模数。 那么我们如何向机器解释结果应该是什么

A+B-M

if (high_A <= ULLONG_MAX - high_B) flag_h = 0; else flag_h = 1;
if (flag_h) {
    int car = 0;
    high_A = high_A - high_M;
    high_B = high_B - high_M;
    high_C = high_A + high_B + high_M;
    if (low_C <= low_M)
    {
        low_C = low_M - low_C;
        low_C = ULLONG_MAX - low_C + 1;
        car = 1;
    }
    else { low_C = low_C - low_M; }
    high_C -= car;
}

我尝试以上述方式执行此操作,但程序仍然发现错误。 我解释一下我想做什么。我试着制作一个数学公式(A-M) + (B-M) + M = (A + B-M)。我试图从高级和初级水平中减去。 让我们来看看数字

_ 51
  38
 1) 8-1 = 7, 7 more will have to be subtracted
 2) We simulate a loan at the senior level
 3) 10-7 = 9 + 1 - 7 = 3
 4) Set loan flag in the unit
 5) 5 - 3 - flag = 1
 6) 13

1 个答案:

答案 0 :(得分:1)

我找到问题的解决方案,开始从更高的顺序中减去,这里是代码

if (flag_h) 
{
    int car = 0;
    unsigned __int64 temp1,temp2;
    if (high_C < high_M)
    {
        temp1 = high_M - high_C;
        high_C = ULLONG_MAX - temp1 + 1;
    }
    else { high_C = high_C - high_M; }
    if (low_C < low_M) {
        temp2 = low_M - low_C;
        low_C = ULLONG_MAX - temp2 + 1;
        high_C--;
    }
    else { low_C = low_C - low_M; }
}