2012-07-24 11:54:52 8 Comments

**Math**:

If you have an equation like this:

```
x = 3 mod 7
```

x could be ... -4, 3, 10, 17, ..., or more generally:

```
x = 3 + k * 7
```

where k can be any integer. I don't know of a modulo operation is defined for math, but the factor ring certainly is.

**Python**:

In Python, you will always get non-negative values when you use `%`

with a positive `m`

:

```
#!/usr/bin/python
# -*- coding: utf-8 -*-
m = 7
for i in xrange(-8, 10 + 1):
print(i % 7)
```

Results in:

```
6 0 1 2 3 4 5 6 0 1 2 3 4 5 6 0 1 2 3
```

**C++:**

```
#include <iostream>
using namespace std;
int main(){
int m = 7;
for(int i=-8; i <= 10; i++) {
cout << (i % m) << endl;
}
return 0;
}
```

Will output:

```
-1 0 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 0 1 2 3
```

**ISO/IEC 14882:2003(E) - 5.6 Multiplicative operators:**

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not,

the sign of the remainder is implementation-defined 74).

and

74) According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero.

Source: ISO/IEC 14882:2003(E)

(I couldn't find a free version of `ISO/IEC 1539:1991`

. Does anybody know where to get it from?)

The operation seems to be defined like this:

**Question**:

Does it make sense to define it like that?

What are arguments for this specification? Is there a place where the people who create such standards discuss about it? Where I can read something about the reasons why they decided to make it this way?

Most of the time when I use modulo, I want to access elements of a datastructure. In this case, I have to make sure that mod returns a non-negative value. So, for this case, it would be good of mod always returned a non-negative value. (Another usage is the Euclidean algorithm. As you could make both numbers positive before using this algorithm, the sign of modulo would matter.)

**Additional material**:

See Wikipedia for a long list of what modulo does in different languages.

### Related Questions

#### Sponsored Content

#### 5 Answered Questions

### [SOLVED] Why does changing 0.1f to 0 slow down performance by 10x?

**2012-02-16 15:58:39****Dragarro****138210**View**1497**Score**5**Answer- Tags: c++ performance visual-studio-2010 compilation floating-point

#### 25 Answered Questions

### [SOLVED] Why do we need virtual functions in C++?

**2010-03-06 07:10:35****Jake Wilson****524226**View**1230**Score**25**Answer- Tags: c++ virtual-functions

#### 12 Answered Questions

#### 7 Answered Questions

### [SOLVED] C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

**2011-06-11 23:30:14****Nawaz****209210**View**1820**Score**7**Answer- Tags: c++ multithreading c++11 language-lawyer memory-model

#### 10 Answered Questions

### [SOLVED] Why is reading lines from stdin much slower in C++ than Python?

**2012-02-21 02:17:50****JJC****246586**View**1746**Score**10**Answer- Tags: python c++ benchmarking iostream getline

#### 1 Answered Questions

### [SOLVED] Understanding Mod Operator in Math vs Programming

**2019-04-14 00:35:55****csguy****289**View**1**Score**1**Answer- Tags: modulo modulus modular-arithmetic

#### 12 Answered Questions

### [SOLVED] JavaScript % (modulo) gives a negative result for negative numbers

**2010-12-17 03:55:33****Alec Gorge****66660**View**224**Score**12**Answer- Tags: javascript math modulo

## 3 comments

## @Jive Dadson 2018-01-24 09:51:22

Back in the day, someone designing the x86 instruction set decided it was right and good to round integer division toward zero rather than round down. (May the fleas of a thousand camels nest in his mother's beard.) To keep some semblance of math-correctness, operator REM, which is pronounced "remainder", had to behave accordingly. DO NOT read this: https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_73/rzatk/REM.htm

I warned you. Later someone doing the C spec decided it would be conforming for a compiler to do it either the right way or the x86 way. Then a committee doing the C++ spec decided to do it the C way. Then later yet, after this question was posted, a C++ committee decided to standardize on the wrong way. Now we are stuck with it. Many a programmer has written the following function or something like it. I have probably done it at least a dozen times.

There goes your efficiency.

These days I use essentially the following, with some type_traits stuff thrown in. (Thanks to Clearer for a comment that gave me an idea for an improvement using latter day C++. See below.)

True fact: I lobbied the Pascal standards committee to do mod the right way until they relented. To my horror, they did integer division the wrong way. So they do not even match.

EDIT: Clearer gave me an idea. I am working on a new one.

## @Clearer 2018-01-24 10:17:37

Wouldn't an assert that

`a % b >= 0`

be the right thing? Some platform may define`a % b`

, to do the right thing (by accident, extension of willful rebellion) and assert that`a % b >= 0`

.## @Jive Dadson 2018-01-24 10:30:57

@Clearer - No, but you gave me a good idea. See the edited answer.

## @gornvix 2018-01-29 19:35:39

I got your inline function to work, but my compiler gave an error: expected primary-expression before â€˜constexprâ€™. I'm using GCC with -std=c++14.

## @Jive Dadson 2018-01-29 19:47:09

@tyebillion "if constexpr" is a C++17 thing.

## @ToolmakerSteve 2019-01-23 22:53:47

@Clearer - the assert says "this function isn't designed to handle negative b". If you want to allow

`b`

to be negative, you need a more complex solution. [Usually`b`

is known to be positive, it is just`a`

that has the pesky tendency to be negative sometimes]## @ecatmur 2012-07-24 12:43:05

On x86 (and other processor architectures), integer division and modulo are carried out by a single operation,

`idiv`

(`div`

for unsigned values), which produces both quotient and remainder (for word-sized arguments, in`AX`

and`DX`

respectively). This is used in the C library function`divmod`

, which can be optimised by the compiler to a single instruction!Integer division respects two rules:

`dividend = quotient*divisor + remainder`

is satisfied by the results.Accordingly, when dividing a negative number by a positive number, the quotient will be negative (or zero).

So this behaviour can be seen as the result of a chain of local decisions:

## @supercat 2013-12-19 09:10:52

I wonder how often the truncated division is faster than floored, given that power-of-two divisors are very common, as are divisors which are amenable to scaled multiplication.

## @fredoverflow 2012-07-24 12:08:30

One of the design goals of C++ is to map efficiently to hardware. If the underlying hardware implements division in a way that produces negative remainders, then that's what you'll get if you use

`%`

in C++. That's all there is to it really.You will find interesting discussions on comp.lang.c++.moderated and, to a lesser extent, comp.lang.c++

## @Preet Kukreti 2012-07-24 12:12:49

And this goes very well with the C++ goal of "you dont pay for what you dont use". Performance is never sacrificed by default for the sake of convenience. If you need to check/

`abs`

your modulo results, you can easily wrap it wherever you need that behavior.## @supercat 2013-11-01 21:32:47

Wouldn't the goal of "mapping efficiently to hardware" be better specified by saying that if x or y is negative and the modulus is non-zero, the compiler could arbitrarily return either the positive or negative result? The fastest implementation of (x%123456789) which works correctly with positive numbers might yield negative results with negative numbers, but the fastest implementation of (x%8) would yield positive numbers. The fastest way to compute (x mod y) if y is positive and x may be negative is probably:

`m=x%y; if (m<0) m+=y;`

, and that would work even if the compiler...## @supercat 2013-11-01 21:37:15

...randomly returned positive or negative results for negative x values that weren't divisible by y. The only thing I can see that is accomplished by specifying truncate-to-zero on

`/`

, and corresponding behavior on`%`

, is to make operations like`x/=4;`

or`y%=4;`

three times as slow as they would otherwise need to be. Have you ever seen any code that actually benefits from -5%2=-1?## @Jive Dadson 2018-01-24 10:43:27

@Preet - I always want modulo to work the right way, so I always pay for it.