获得模数和除法结果的最佳方法?
鉴于模除法和整数除法密切相关,您可能会认为在一次操作中获取这两个值是有意义的。有没有具有这种功能的语言?
后续问题:对于不具备此功能的语言,是否最好通过减去除法 * 分母的结果来计算模数?
// In java, if I want both values I need to do this:
int myNumber = 125;
int denominator = 6;
int division = myNumber / denominator; // 20
int modulo1 = myNumber % denominator; // 5
// Follow up: Is this a more efficient way to compute the modulo?
int modulo2 = myNumber - division * denominator;
Seeing as modulo and integer division are closely related, you'd think it would make sense to get both values in one operation. Are there languages that have this capability?
Follow up question: For languages that don't have this capability, is it best to compute the modulo by subtracting off the result of the division * denominator?
// In java, if I want both values I need to do this:
int myNumber = 125;
int denominator = 6;
int division = myNumber / denominator; // 20
int modulo1 = myNumber % denominator; // 5
// Follow up: Is this a more efficient way to compute the modulo?
int modulo2 = myNumber - division * denominator;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 BigInteger 时,您可以在一次运算中查询商和余数。
但是,当您使用整数值进行计算时,最好信任 JIT 编译器/热点优化器。
例如,当我经常使用
和运行
test(125, 6)
时,我会得到以下使用 JDK 11/x86 编译的本机代码我们可以清楚地看到这两个操作,
myNumber / 分母
和myNumber % denominator
已融合到单个idiv
指令中。When you use
BigInteger
, you can query quotient and remainder in one operationHowever, when you are calculating with integral values, it’s best to trust the JIT compiler/ hotspot optimizer.
E.g. when I use
and run
test(125, 6)
often enough, I get the following compiled native code with JDK 11/x86We can clearly see that the two operations,
myNumber / denominator
andmyNumber % denominator
have been fused into a singleidiv
instruction.