簡體   English   中英

對於無符號長A和B,有沒有辦法(A * B)mod M沒有溢出?

[英]Is there a way to do (A*B) mod M without overflow for unsigned long long A and B?

我不想在Windows上安裝GMP的噩夢。

我有兩個數字A和B, unsigned long long s,大約10 ^ 10左右,但即使做((A%M)*(B%M))%M ,我得到整數溢出。

是否有自制函數用於計算較大數字的(A*B)%M

如果模數M遠小於ULLONG_MAX (如果它在10 ^ 10的范圍內就是這種情況),則可以通過將兩個因子中的一個分成兩部分來分三步完成。 我假設A < MB < M ,且M < 2^42

// split A into to parts
unsigned long long a1 = (A >> 21), a2 = A & ((1ull << 21) - 1);
unsigned long long temp = (a1 * B) % M;   // doesn't overflow under the assumptions
temp = (temp << 21) % M;                  // this neither
temp += (a2*B) % M;                       // nor this
return temp % M;

對於較大的值,您可以將因子分成三個部分,但如果模數真的接近ULLONG_MAX則變得難看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM