Tag: modulo

当`if(变量%2 == 0)`时程序崩溃

我正在写一个找到完美数字的程序。 读完这些完美的数字之后,我遇到了一个列表: 完美数字列表 。 目前的输出是: 28 // perfect 496 // perfect 8128 // perfect 130816 // not perfect 2096128 // not perfect 33550336 // perfect 我决定创建数组并使用数字,将数字全部除以(不包括其余数字)。 因此,通过添加数组的所有元素,我将能够validation它是否是一个完美的数字。 但应用程序崩溃,我无法理解为什么: #include #include int main() { unsigned long number; unsigned long arr2[100] = {0}; int k = 0; for ( number = 0; number <= 130816; number++ ) […]

消除模偏差:如何在arc4random_uniform()函数中实现?

模数偏差是在天真地使用模运算来获得小于给定“上限”的伪随机数时出现的问题。 因此,作为C程序员,我使用arc4random_uniform()函数的修改版本来生成均匀分布的伪随机数。 问题是我不明白这个函数是如何工作的,数学上。 这是函数的解释性注释,后跟完整源代码的链接: /* * Calculate a uniformly distributed random number less than upper_bound * avoiding “modulo bias”. * * Uniformity is achieved by generating new random numbers until the one * returned is outside the range [0, 2**32 % upper_bound). This * guarantees the selected random number will be inside * [2**32 % […]

INT_MIN%-1是否会产生未定义的行为?

gcc生成浮动代码,为以下代码引发SIGFPE : #include int x = -1; int main() { return INT_MIN % x; } 但是,我在标准中找不到此代码调用未定义或实现定义的行为的语句。 据我所知,它需要返回0.这是gcc中的错误还是我错过了标准所做的一些特殊例外?