How to make the mod of a negative number to be positive?

后端 未结 6 1196
独厮守ぢ
独厮守ぢ 2021-02-18 13:03

Basically, I need (-3) % 5 to be \"2\" instead of \"-3\". Python produces \"2\", but C++ produces \"-3\". Not sure how to produce \"2\" in C++. Thanks!

6条回答
  •  鱼传尺愫
    2021-02-18 13:34

    You can add some multiple of 5 to the negative number first, to convert it to a positive number with the same value mod 5.

    You can do that by taking the absolute of the negative number, adding whatever is needed to round it up to the next multiple of 5, and then add it to your negative number, and that should already be a number between 0 and 4.

    Alternatively, simply do something like:

    num = -2;
    mod = 5;
    if ( num < 0 ) {
        result = mod - (abs(num) % mod);
    }
    

    and it'll work (explanation: mathemagic)

提交回复
热议问题