Exercise 10 of 30 · intermediate · loops · square root · primes

Loop until i² exceeds n

The code

i = 1
while i * i <= n:      # e.g. trial division up to √n
    if n % i == 0: ...
    i += 1

How many iterations?

Count: iterations.

Measured counts

020406020004000ncount
Measured
Table
ncount
82
164
325
648
12811
25616
51222
102432
204845
409664

Try to name the class from the shape before opening the answer.

Show the answer and derivation
Time
Θ(√n)
Extra space
O(1)
Exact count
⌊√n⌋
  1. The loop continues while i ≤ √n.
  2. i grows by 1, so it runs ⌊√n⌋ times.
  3. This is why trial division checks divisors only up to √n.

Common mistake: Answering O(log n). i grows by 1, not geometrically; the bound is √n.

Check: measured count ÷ (√n) settles near 1.00 for large n.