Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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!

like image 370
Hailiang Zhang Avatar asked Dec 10 '12 02:12

Hailiang Zhang


People also ask

Can you do mod of a negative number?

The modulus of a negative number is found by ignoring the minus sign. The modulus of a number is denoted by writing vertical lines around the number. Note also that the modulus of a negative number can be found by multiplying it by −1 since, for example, −(−8) = 8.


2 Answers

Most easily: ((x % 5) + 5) % 5

like image 194
ysth Avatar answered Sep 20 '22 05:09

ysth


Add the base if the input number X is negative:

X % Y + (X % Y < 0 ? Y : 0); 
like image 40
perreal Avatar answered Sep 24 '22 05:09

perreal