What is the difference of int(n/2) and n//2 in python?

Jimmy (xiaoke) Shen
1 min readFeb 10, 2024

--

Today I got stuck in an intersting problem. I am not sure the reason until I realize that there is some difference of

int(n / 2) and n // 2 in python under some scenario.

The problem

https://atcoder.jp/contests/abc340/tasks/abc340_c

v1 (using int( n / 2), which has issue)

from functools import lru_cache                                                         
N = int(input())
@lru_cache(None)
def f(n):
if n <= 1:
return 0
else:
half = int(n / 2)
if n % 2 == 0:
return n + 2*(f(half))
else:
return n + f(half) + f(half + 1)
print(f(N))

the output

1000000000000000000000000000000000
109701925785366288902160823344955392

v2 (using n//2, which works)

from functools import lru_cache                                                         
N = int(input())
@lru_cache(None)
def f(n):
if n <= 1:
return 0
else:
half = n // 2
if n % 2 == 0:
return n + 2*(f(half))
else:
return n + f(half) + f(half + 1)
print(f(N))

The output

1000000000000000000000000000000000
109701925785366293092867375917694976

They have different outputs for the following input

1000000000000000000000000000000000

The reason goes to the floating point number is not very accurate when the number is too large.

>>> 1000000000000000000000000000000000//2
500000000000000000000000000000000
>>> 1000000000000000000000000000000000/2
5e+32
>>> int(1000000000000000000000000000000000/2)
499999999999999972787615493521408

--

--