Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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]

Solution 2:

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


Solution 3:

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, i.e. 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. ;)


Solution 4:

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.


Solution 5:

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.


Post a Comment for "List All Factors Of Number"