List All Factors Of Number
Solution 1:
This can be done on one line using list comprehension.
deffactorize(num):
return [n for n inrange(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 = ""deffindFactor(count):
divisors = ""
valueD = 0for i inrange(1, count+1):
valueD = count/i
ifisinstance(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.
deffindFactor(n):
factorValues = []
for i inrange(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 factorsprint 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 // iif i > j:
breakreturn 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"