How to calculate -1 modulo 1000000007 in C ++

I tried to get the result -1 modulo 1000000007 using the %C ++ and operator fmod.
Output signal -1but -1 modulo 1000000007==1000000006.

What did I do wrong?

+4
source share
2 answers

Just said that you took the wrong operator.

C ++ and C are % not modulo, but the remainder.

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

If anon-negative, modulo and remainder are the same.

Otherwise, the return value is negative, just add 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;
}

Or (also) for C:

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

: ++ 11, a / b , 0, ++ 03 , , , 0.

:

Modulo - 0 <= <

+8

Modulo, , :

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

All Articles