简体   繁体   中英

List all factors of number

I am trying to list all the factors of a number called count. Whenever I run it, it returns 1. For example: if 6 = count , then what should be returned when calling findFactor(6) is 1 2 3 6 . What is returned is 1

divisors = ""
def findFactor(count):
    divisors = ""
    valueD = 0
    for i in range(1, count+1):
        valueD = count/i
        if isinstance(valueD,int) == True:
            divisors = str(valueD)+" "
    print divisors

This can be done on one line using list comprehension .

def factorize(num):
    return [n for n in range(1, num + 1) if num % n == 0]

You can refer this code:

def find_factor(n):
  factor_values = []
  for i in range(1, n + 1):
    if n % i == 0:
      factor_values.append(i)

  values = ""
  for v in factor_values:
    values += str(v) + " "

  return values

The function will return 1 2 3 6

First of all, you have an indentation error. print divisors need to be tabbed to inside the for-loop.

divisors = ""
def findFactor(count):
    divisors = ""
    valueD = 0
    for i in range(1, count+1):
        valueD = count/i
        if isinstance(valueD,int) == True:
            divisors = str(valueD)+" "
        print divisors

Furthermore like @juanpa.arrivillaga mentioned, your results will vary between Python 2 and Python 3.

However, if you want your divisors to print in the order you want, ie start with 1 you need to change your range to for i in range(count,0, -1) . You will get multiple 1 's , but that's something I'll leave for you to figure out. A little challenge, if you will. ;)

This is the total code I have come up with. Thank you for all the help.

def findFactor(n):
  factorValues = []
  for i in range(1, n + 1):
    if n % i == 0:
      factorValues.append(i)

  values = ""
  for v in factorValues:
    values += str(v) + " "

  print values.count(" ")
  # prints the number of factors


  print values
findFactor(21)

It will print the number of factors, and then the factors on the next line.

The answers given so far are all brute force methods.

For n=10000, they will have to iterate ten thousand times.

The following will iterate only 100 times:

def find_factors(n):
    factors = []
    i = 1
    j = n
    while True:
        if i*j == n:
            factors.append(i)
            if i == j:
                break
            factors.append(j)
        i += 1
        j = n // i
        if i > j:
            break
    return factors

If there were a list of prime numbers available, it could be made even faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM