12

这种脚本语言没有 % 或 Mod()。我确实有一个 Fix() 可以去掉数字的小数部分。我只需要积极的结果,所以不要太健壮。

4

7 回答 7

21

将要

// mod = a % b

c = Fix(a / b)
mod = a - b * c

做?我假设你至少可以在这里划分。所有的赌注都是负数。

于 2010-05-03T23:55:53.013 回答
6

a mod n = a - (n * Fix(a/n))

于 2010-05-03T23:56:59.547 回答
6

对于后代,BrightScript 现在有一个模运算符,它看起来像这样:

c = a mod b
于 2015-05-29T17:54:28.567 回答
2

如果有人迟到,这里有一些更实际的算法(有错误......仔细阅读)

https://eprint.iacr.org/2014/755.pdf

实际上有两种主要的归约公式:Barett 和 Montgomery。来自 eprint 的论文在不同版本(算法 1-3)中重复,并在算法 4 中给出了“改进”版本。

概述

我现在概述一下 4. 算法:

1.) 计算“A*B”并将整个乘积存储在“C”中,C 和模 $p$ 是该算法的输入。

2.) 计算 $p$ 的位长,例如:函数“Width(p)”准确地返回那个值。

3.) 将输入 $C$ 拆分为大小为“Width(p)”的 N 个“块”,并将每个“块”存储在 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

这确实很多。我们不仅需要递归地减少 G[0]:

while G[0] > p do
    G[0] -= p
endwhile
return G[0]// = C mod p

其他三种算法定义明确,但这缺少一些信息或显示它确实是错误的。但它适用于任何尺寸;)

于 2017-11-15T13:51:02.067 回答
1

它是什么语言?

一个基本算法可能是:

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;
  }
}
于 2010-05-04T00:00:31.157 回答
0

这在性能方面可能对您不起作用,但是:

while (num >= mod_limit)
    num = num - mod_limit
于 2010-05-03T23:56:24.947 回答
0

在 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;
}
于 2017-03-09T23:13:02.013 回答