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

This worked.

Answers


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.


Need Your Help

How to create new client certificates / tokens for programmatic access to the Kubernetes API hosted on GKE?

go google-cloud-platform kubernetes google-kubernetes-engine

I am running a Kubernetes cluster hosted on GKE and would like to write an application (written in Go) that speaks to the Kubernetes API. My understanding is that I can either provide a client

VB.NET - Genetic Algotithm - Knapsack Problem

vb.net algorithm genetic-algorithm knapsack-problem

I have been working on the Knapsack problem using genetic algorithms. But I have run into a few difficulties...