Skip to main content

sqrt, ceil, floor

math.isqrt gives the exact integer square root (no float error); math.sqrt returns a float. ceil/floor/trunc round floats to ints. Prefer integer-only ceil division to avoid float precision bugs (e.g. Koko Eating Bananas).

Syntax​

import math

math.isqrt(17) # -> 4 floor(sqrt(n)), exact for any int size
math.sqrt(17) # -> 4.123105625617661
math.ceil(2.1) # -> 3
math.floor(-2.1) # -> -3

Perfect square check​

import math

def is_square(n: int) -> bool:
r = math.isqrt(n) # ValueError for n < 0
return r * r == n

is_square(10**30) # -> True
# int(math.sqrt(n)) ** 2 == n can fail for large n due to float rounding

Iterate up to sqrt(n)​

import math

def divisors(n: int) -> list[int]:
res = []
for i in range(1, math.isqrt(n) + 1): # O(sqrt n)
if n % i == 0:
res.append(i)
if i != n // i:
res.append(n // i)
return sorted(res)

divisors(36) # -> [1, 2, 3, 4, 6, 9, 12, 18, 36]

Ceil division (integers only)​

a, b = 7, 2
-(-a // b) # -> 4 works for negatives too
(a + b - 1) // b # -> 4 positive a, b only
# hours to eat a pile of size p at speed k: -(-p // k)

floor vs trunc vs int vs round​

import math

math.floor(-2.5) # -> -3 toward -inf
math.trunc(-2.5) # -> -2 toward 0
int(-2.5) # -> -2 same as trunc
round(2.5) # -> 2 banker's rounding (half to even)
round(3.5) # -> 4
-7 // 2 # -> -4 // floors, not truncates

Integer floor division vs math.floor​

import math

a, b = 10**18 + 1, 3
a // b # exact
math.floor(a / b) # float division first, may be off for big ints

Docs​