DEV Community

Cover image for Finding Divisors of a Number
hebaShakeel
hebaShakeel

Posted on

Finding Divisors of a Number

Ok so now your interviewer asks you to write a program to find all the divisors of a number. What would be your solution.
Example:
if NUM = 6
Divisors of 6 are 1 2 3 6.

NAIVE SOLUTION:
Image description

Time Complexity : Θ(n)
Space Complexity: O(1)

EFFICIENT SOLUTION:
Image description

Time Complexity : Θ(√n)
This solution does not print the divisors in sorted order.

To print in sorted order:
Image description

Time Complexity : Θ(√n)
Space Complexity : O(1)

Do you have a better solution in mind?
Do share in the comments!

Discussion (0)