python - generator yield factors in increasing order (beginner)
I'm working my way through (beginner) exercises in a Python book and I'm having troubles with one of the exercises.
The exercise: modify this generator so that it reports factors in increasing order, while maintaining its general performance advantages (= testing values only up to the square root of the number).
def factors(n): k = 1 while k*k < n: if n%k == 0: yield k yield n // k k += 1 if k*k == n: yield k
Can somebody point me in the right direction?
EDIT : After the answer I got from NPE, I changed the code into:
def factors(n): k = 1 temp =  while k*k < n: if n%k == 0: yield k temp.append(n // k) k += 1 if k*k == n: yield k for i in reversed(temp): yield i
Except for the n // k, the factors are already being produced in increasing order.
Instead of yielding n // k immediately, you could remember such factors and yield them at the end.