【发布时间】:2018-10-20 18:41:04
【问题描述】:
我正在尝试制作一个快速计算 x^y mod z 的函数。它在计算 2^63 mod 3 之类的东西时效果很好,但在 2^64 mod 3 和更高的指数时,它只返回 0。
我怀疑某处有溢出,但我无法确定。我已经在进行计算(* 和 mod)的地方尝试了显式转换,我还设置了我的存储变量(resPow,curPow)unsigned long long int(建议 here)但这没有帮助很多。
typedef unsigned long int lint;
lint fastpow(lint nBase, lint nExp, lint nMod) {
int lastTrueBit = 0;
unsigned long long int resPow = 1ULL;
unsigned long long int curPow = nBase;
for (int i = 0; i < 32; i++) {
int currentBit = getBit(nExp, i);
if (currentBit == 1) {
for (lint j = 0; j < i - lastTrueBit; j++) {
curPow = curPow * curPow;
}
resPow =resPow * curPow;
lastTrueBit = i;
}
}
return resPow % nMod;
}
【问题讨论】:
-
为什么最后只做
% nMod?这违背了整个目的。 -
你可以用
unsigned计算2^64 mod 3char!
标签: c multiplication exponential unsigned-long-long-int