Integer Division in C++ and in Python

I had not noticed the difference of integer division between C++ and Python, until I was trying to solve this leetcode problem.

This problem is very simple but I got an unexpected WA. After I had done some debugging, I found it out that integer division in Python has a different behavior, comparing that in C++.

In C++, the result of integer division is rounded towards zero.

int x = 3;
int y = -2;
int z = x/y;
printf("%d\n", z);

It will output -1, since the result of 3/(-2) is -1.5 and then it is rounded towards zero.

But Python says differently.

>>> 3/-2
-2
>>> -3/2
-2
>>> -(3/2)
-1

It looks like when doing integer division, python always rounds down.

The following code works, if you want to do a rounding-to-zero integer division in python. A simple math.floor() also does.

def IntegerDivision(x, y):
    z = x / y
    if x % y == 0 and x / y < 0:
        z += 1
    return z

Leave a Reply

Your email address will not be published.

− 4 = 6