c++ - 如何在 C++ 中计算 -1 模 1000000007

标签 c++ algorithm modulo

我尝试使用 C++ 的 % 运算符获得 -1 模 1000000007 的结果 和 fmod功能。
输出为 -1,但 -1 modulo 1000000007==1000000006

我做错了什么?

最佳答案

说白了,你拿错算子了。

C++ 和 C % 不是模,而是余数。

assert(a / b * b + a % b == a); // for integral types

如果a是非负数,则模数和余数相同。

否则返回值为负,只需添加b

template<class T>
inline constexpr auto
modulo(T a, T b) -> decltype(a%b) {
    auto r = a % b;
    if (r < 0) r += b;
    return r;
}

或者(也)对于 C:

#define modulo(a, b) (a % b < 0 ? a % b + b : a % b)

为了完整性:在 C++11 之前,a/b 可以总是向下舍入而不是总是为 0,尽管 C++03 已经有一个注释,下一个标准可能会强制舍入到0.

See Wikipedia on modulo :

Modulo is the remainder of euclidiean division, and always in range 0 <= modulo < divisor

And on remainder :

In mathematics, the remainder is the amount "left over" after performing some computation.

关于c++ - 如何在 C++ 中计算 -1 模 1000000007,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26079469/

相关文章:

batch-file - 批处理文件计算器除法余数

c++ - 为什么人们说使用随机数生成器时存在模偏差?

python - 如何在Python中反转%操作

c++ - 无缓冲 I/O 不工作

绘图仪GUI组件中标尺自缩放算法

algorithm - 至少共享一个数字的对数

javascript - 在 Javascript 中比较两个对象数组与文字值的更快方法

c++ - DirectShow 中是否有任何受支持的高位深度视频或图像格式

c++ - 在未评估的上下文中获取成员参数函数的返回类型

c++ - Exe 在 BackupRead Windows 函数中崩溃