2012-11-20 24 views

回答

9

如果模量M足夠小於ULLONG_MAX(如果它在10^10的範圍內,則是這種情況),您可以通過將兩個部分中的一個分解爲三個步驟來完成。我假設A < MB < MM < 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變得難看。

+0

Sweet googly mooglies,我相信這是有效的。謝謝 –

相關問題