什么是有效的方式来获得在C至少非负残模n? [英] What is an efficient way to get the least non-negative residue modulo n in C?
问题描述
是否有一个有效的方式来获得至少非负残留模n,其中n为正,在C
Is there an efficient way to get the least non-negative residue modulo n, where n is positive, in C?
这是如果数字为非负相当容易的,那么它只是一个%n(其中一个是所述非负整数)。
This is quite easy if the number is non-negative, then it's just a % n (where a is the non-negative integer).
然而,当一个是负的,它出现的行为,在C89,是实现定义(感谢kennyTM)。即-2%11 = -2或9。
However when a is negative, it appears the behaviour, in C89, is implementation defined (thanks kennyTM). I.e. -2 % 11 = -2 or 9.
推荐答案
此外,在C99中的行为被定义为恼人之一:-2%11 = -2
Furthermore, in C99 the behaviour is defined to be the annoying one: -2 % 11 = -2.
在一般(即ñ%M
在 M
不是恒定的范围<$ C $ ç> N 是不受约束的),你可能无法做得比通常的
In general (i.e., n % m
when m
is not constant and the range of n
is unconstrained), you probably can't do better than the usual
res = ((n % m) + m) % m
这可能要比较,为你的平台上下面是有趣的;一个分支可能战胜额外模:
It may be interesting to compare that to the following on your platform; one branch might win against the extra modulo:
res = n % m;
if (res < 0) res += m;
这篇关于什么是有效的方式来获得在C至少非负残模n?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!