16

可能重复:
识别何时使用 mod 运算符

模数的实际用途是什么?我知道模除法是什么。我想到的第一个场景是用它来查找奇数和偶数以及时钟算术。但是我还能在哪里使用它?

4

9 回答 9

25

我发现最常见的用途是“环绕”您的数组索引。

例如,如果您只想重复循环遍历一个数组,您可以使用:

int a[10];
for (int i = 0; true; i = (i + 1) % 10)
{
  // ... use a[i] ...
}

模确保i保持在 [0, 10) 范围内。

于 2010-08-28T08:06:32.377 回答
8

我通常在紧密的循环中使用它们,当我必须在每个 X 循环而不是每次迭代时都做一些事情时..

例子:

int i;
for (i = 1; i <= 1000000; i++)
{
   do_something(i);
   if (i % 1000 == 0)
       printf("%d processed\n", i);
}
于 2010-08-28T09:11:58.363 回答
6

要将数字打印为字符串,您需要模数来查找数字的值。

string number_to_string(uint number) {
  string result = "";
  while (number != 0) {
    result = cast(char)((number % 10) + '0') ~ result;
    //                   ^^^^^^^^^^^
    number /= 10;
  }
  return result;
}
于 2010-08-28T08:06:19.480 回答
5

模运算的一种用途是在制作哈希表时。它用于将散列函数中的值转换为数组的索引。(如果哈希表大小是 2 的幂,则可以使用位掩码进行取模,但它仍然是取模操作。)

于 2010-08-28T08:11:39.843 回答
5

对于国际银行帐号的控制号码,mod97技术

n也是在大批量迭代之后做一些事情。这是NHibernate的示例:

ISession session = sessionFactory.openSession();
ITransaction tx = session.BeginTransaction();

for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.Save(customer);
    if ( i % 20 == 0 ) { //20, same as the ADO batch size
        //Flush a batch of inserts and release memory:
        session.Flush();
        session.Clear();
    }
}

tx.Commit();
session.Close();
于 2010-08-28T09:57:57.040 回答
3
  • 密码学。仅此一项就占模数的一个令人讨厌的百分比(我夸大了,但你明白了)。

也试试维基百科页面

模算术在数论、群论、环论、结论、抽象代数、密码学、计算机科学、化学以及视觉和音乐艺术中被引用。

以我的经验,任何足够先进的算法都可能涉及上述主题中的一个。

于 2010-08-28T08:07:28.073 回答
3

好吧,您可以从很多角度看待它。如果您将其视为数学运算,那么它只是一个模除法。即使我们不需要像 % 那样做任何事情,我们也可以使用减法来实现,但是每种编程语言都以非常优化的方式实现它。

并且模除不限于求奇偶数或时钟算术。有数百种算法需要这个模块运算,例如密码学算法等。所以它是一个通用的数学运算,就像其他+,-,*,/等一样。

除了数学的观点,不同的语言使用这个符号来定义内置的数据结构,就像在 Perl%hash中用来表明程序员声明了一个散列。因此,这一切都因编程语言设计而异。

所以仍然有很多其他的观点可以添加到 % 的使用列表中。

于 2010-08-28T08:12:04.670 回答
3

缓冲通信的通常实现使用循环缓冲区,并且您使用模数算法来管理它们。

于 2010-08-28T08:12:45.163 回答
3

For languages that don't have bitwise operators, modulus can be used to get the lowest n bits of a number. For example, to get the lowest 8 bits of x:

x % 256

which is equivalent to:

x & 255
于 2010-08-28T08:15:51.670 回答