I was asked to create a function that is given a positive integer num
, and returns a generator, that when iterated over, it will return all of num
's divisors in ascending order.
Implementation requirements:
- Runtime of O(sqrt(n))
- Memory complexity of O(1)
I was able to meet the runtime requirement but couldn't figure out to solve the problem in O(1) memory (ie. without using a list, tuple, string etc.)
Here's my code so far.
def factors(num):
higher_divisors = [0] * int(num ** .5)
index = 0
for i in range(1, int(num ** .5) + 1):
if num % i == 0:
yield i
if i != num // i: # don't include the square root twice
higher_divisors[index] = num // i
index += 1
for i in range(index - 1, -1, -1): # yield the higher divisors in reverse order
yield higher_divisors[i]
def main():
num = 100
for i in factors(num):
print(i)
if __name__ == "__main__":
main()