这种脚本语言没有 % 或 Mod() 运算符。我有一个 Fix() 函数,可以将一个数的小数部分截取掉。我只需要正数结果,所以不需要太复杂。
这种脚本语言没有 % 或 Mod() 运算符。我有一个 Fix() 函数,可以将一个数的小数部分截取掉。我只需要正数结果,所以不需要太复杂。
将会
// mod = a % b
c = Fix(a / b)
mod = a - b * c
你会做除法吗?我默认你至少会在这里进行除法运算。但是如果涉及到负数,一切皆有可能。
fix()
函数,它总是截断小数部分,还有一个int()
函数,它总是向下舍入(int(-2.5)=-3
)。 - Nas Banov为了后人,BrightScript现在有一个模运算符,它看起来像这样:
c = a mod b
a mod n = a - (n * Fix(a/n))
https://eprint.iacr.org/2014/755.pdf
实际上有两种主要的约减公式:Barett 和 Montgomery。eprint 上的论文在不同版本(算法1-3)中重复了这两种公式,并在算法4中给出了一种“改进”的版本。
现在我将对第四个算法进行概述:
1.) 计算“A*B”,并将整个乘积存储在“C”中,其中C和模$p$是该算法的输入。
2.) 计算$p$的位数,即函数“Width(p)”返回确切的值。
3.) 将输入$C$分成N个大小为“Width(p)”的“块”,并将每个块存储在G中。从G[0] = lsb(p)开始,以G[N-1] = msb(p)结束。(论文描述真的很有问题)
4.) 开始while循环: 设置N=N-1(达到最后一个元素) 预计算$b:=2^{Width(p)} \bmod p$
while N>0 do:
T = G[N]
for(i=0; i<Width(p); i++) do: //Note: that counter doesn't matter, it limits the loop)
T = T << 1 //leftshift by 1 bit
while is_set( bit( T, Width(p) ) ) do // (N+1)-th bit of T is 1
unset( bit( T, Width(p) ) ) // unset the (N+1)-th bit of T (==0)
T += b
endwhile
endfor
G[N-1] += T
while is_set( bit( G[N-1], Width(p) ) ) do
unset( bit( G[N-1], Width(p) ) )
G[N-1] += b
endwhile
N -= 1
endwhile
while G[0] > p do
G[0] -= p
endwhile
return G[0]// = C mod p
这是什么语言?
一个基本的算法可能是:
hold the modulo in a variable (modulo);
hold the target number in a variable (target);
initialize modulus variable;
while (target > 0) {
if (target > modulo) {
target -= modulo;
}
else if(target < modulo) {
modulus = target;
break;
}
}
target==modulo
的情况下存在错误。会导致无限循环。 - Ice-Blaze这个可能在性能方面对你不起作用,但是:
while (num >= mod_limit)
num = num - mod_limit
在JavaScript中:
function modulo(num1, num2) {
if (num2 === 0 || isNaN(num1) || isNaN(num2)) {
return NaN;
}
if (num1 === 0) {
return 0;
}
var remainderIsPositive = num1 >= 0;
num1 = Math.abs(num1);
num2 = Math.abs(num2);
while (num1 >= num2) {
num1 -= num2
}
return remainderIsPositive ? num1 : 0 - num1;
}