It works because if n is divisible by 2 then it is also divisible by n / 2, and if it is not divisible by one, it won't be divisible by the other either. So it's enough to check one of them, and 2 is more convenient to check.
The same logic applies for 3: (lack of) divisibility by 3 implies (lack of) divisibility by n / 3, so it suffices to only check 3.
The same will apply for 4, 5, ..., x. What is x? It's sqrt(n), because n / sqrt(n) = sqrt(n), so things will start repeating after this threshold.
It is enough to check up to and including floor(sqrt(n)). We can prove this:
floor(sqrt(n)) <= ceil(sqrt(n))
For the "=" part, it's obvious both work.
floor(sqrt(n)) < ceil(sqrt(n)) <=> floor(sqrt(n)) + 1 = ceil(sqrt(n))
if n divisible by floor(sqrt(n)) + 1 =>
=> n divisible by n / (floor(sqrt(n)) + 1) < n / floor(sqrt(n))
Since we checked all numbers smaller than or equal to floor(sqrt(n)), we would have found the divisor n / (floor(sqrt(n) + 1)), so there is no point in checking the ceiling.