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 += 1How many iterations?
Count: iterations.
Measured counts
Table
| n | count |
|---|---|
| 8 | 2 |
| 16 | 4 |
| 32 | 5 |
| 64 | 8 |
| 128 | 11 |
| 256 | 16 |
| 512 | 22 |
| 1024 | 32 |
| 2048 | 45 |
| 4096 | 64 |
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⌋
- The loop continues while i ≤ √n.
- i grows by 1, so it runs ⌊√n⌋ times.
- 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.