# Integer remainder for negative numbers

This is a discussion on Integer remainder for negative numbers within the C Programming forums, part of the General Programming Boards category; Hello, I'm looking for a way in C to get the remainder of a negative number such that the remainder ...

1. ## Integer remainder for negative numbers

Hello, I'm looking for a way in C to get the remainder of a negative number such that the remainder is positive, i.e. using truncation toward negative infinity rather than truncation toward zero.

Example; using the modulus operator, -10%3 returns -1 as it is equivalent to the following:

-10 - 3*int(-10/3) = -10 -3(-3) = -1

I want an expression that returns 2:

-10 - 3*floor(-10/3) = -10 - 3(-4) = 2

I'd like to avoid using a floating point function (floor()); integer math only.

Thanks, Stan

2. Use the positive version of your dividend. You can use a unary - in C to negate something. Say x is -10, y is 3:
Code:
`remainder = x - y * -(-x / y);`

3. Use the abs() labs() or llabs() function as approriate to your variable type.

Code:
```int x = -10;
int y;

y = abs( x % 3);```

4. Code:
```#include <stdio.h>

int main()
{

int x = -10;
int y;
const int mod_value = 3;

y = ((x%mod_value)+mod_value)%mod_value;
printf("%d\n", y);
return 0;
}```
Code stolen from CT used in my modified solution.

Tim S.

5. Originally Posted by stahta01
Code:
```#include <stdio.h>

int main()
{

int x = -10;
int y;
const int mod_value = 3;

y = ((x%mod_value)+mod_value)%mod_value;
printf("%d\n", y);
return 0;
}```
Code stolen from CT used in my modified solution.

Tim S.
That one worked, thanks.

Popular pages Recent additions