1
def factors(n):
for i in reversed(range(1, n+1)):
    if n % i ==0:
        print(i)

This code currently outputs the factors of a number in a new line ex. factors(18) outputs 18 9 6 etc.... How can I make it so when I type

print("factors for 18 are:", factors(18))

Returns a list of

factors of 18: [18,9,6,3,2,1]

Without having print(i) in my function.

2
  • 2
    So basically your question is just "how do I create a list of numbers instead of printing the numbers"? Do you know about the return statement? Commented Sep 22, 2018 at 21:26
  • 1
    BTW, this algorithm is ok for small n, but it gets pretty slow for large n. A simple way to improve it is to save pairs of factors, i and n//i. So if n is a million, you only have to test i upto 1000. Commented Sep 22, 2018 at 21:36

1 Answer 1

2
def factors(n):
  ret = [] #Make an empty array to store number factors
  for i in reversed(range(1, n+1)):
    if n % i ==0:
      ret.append(i) #append factors
  return ret #return array of factors

print("Factors of 18", factors(18))
Sign up to request clarification or add additional context in comments.

1 Comment

I may be doing something wrong but when I run this program I get Factors of 18 [18]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.