# Mod with negatives

This is a discussion on Mod with negatives within the C Programming forums, part of the General Programming Boards category; Hi, Why does C return to me -9 when i calculate, -9 % 26 ? Python gives me what i ...

1. ## Mod with negatives

Hi,

Why does C return to me -9 when i calculate, -9 % 26 ?
Python gives me what i wanted -9 % 26 = 17. .....

I'm wondering if C has an implementation of mod like Python, or how to go about getting a results like Python's.

If there has been a previous discussion on this topic, plz help me to it.....

Thank you!!!

2. I believe the C modulus operator is undefined for negative numbers.

If you want to have a positive number, you could use integer math to solve the problem:
Code:
```int mod(int x, int y)
{
int t = x - ((x / y) * y);
if (t < 0) t += y;
return t;
}```
--
Mats

3. -9 / 26 = 0 with a remainder of -9. I don't know why Python gives 17 (26 + -9?) as the answer.

4. Why should it give you 17?
See above.

Originally Posted by Chris Torek
Anyway, in C, `a % b' is *not* defined as `a mod b', but rather as `a
remainder b'. Because of that, it is not wrong for a % b to be
negative. If you need a mod b, in C, you must define it yourself. The
situation is rather worse in Pascal, where `a remainder b' is quite
literally spelled `a mod b'. This falls afoul of my second footnote
above, and you are on a stronger footing to call this `wrong'---not
because the a mod b does not compute the correct remainder, but rather
because this remainder function has a highly misleading name. This is
why C's `a % b' should not be pronounced `a mod b'.

6. Originally Posted by matsp
I believe the C modulus operator is undefined for negative numbers.
It's not undefined anymore in C99. They finally decided that the mod operator always obeys the following:

Code:
`a * (a / b) + (a % b) == a`
Regardless of what sign any of the quantities are.

7. Originally Posted by karlthetruth
-9 / 26 = 0 with a remainder of -9. I don't know why Python gives 17 (26 + -9?) as the answer.
Probably because Python doesn't specify the behavior either. Notice that 26 - (9 % 26) == 17, which is a typical result on many CPUs.

8. Originally Posted by Dave_Sinkula
I thought 'modulus' is the remainder of a division? What else would it be?

9. Thanks guys for the help...

I got my program fixed already...