Visualize

Pattern visualizer

Print all Divisors

Divisors come in pairs (i, n/i), so it's only necessary to check i up to sqrt(n) — every divisor above that has already been found as the paired n/i of a smaller one. Animated on: n = 36 — list every divisor of n..

Only check up to sqrt(n), pair each divisor with n/i

time O(sqrt(n))space O(d)step 1 / 8
line 3

sqrt(36) = 6, so check i from 1 to 6 — every divisor beyond that already appeared as a pair.

Pseudocode
1FUNCTION printDivisors(n):
2 make an empty list of divisors
3 FOR i from 1 to sqrt(n):
4 IF n is divisible by i:
5 add i and n/i to the list (just once if they are equal)
6 RETURN the divisors in sorted order

← / → step · space play · Home restart

Where to practice Math