I was asked this question in an interview:
Find all the factors of a given natural number, N
1 <= N <= 10**10
Example:
N = 6 => 1, 2, 3, 6
N = 60 => 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60
I wrote following code,but got an feedback that complexity could be improved.
How to optimise following code?
import math
def get_all_factors(n):
ans = [1]
if n==1:
return ans
factors = [False] * n
for i in xrange(2,int(math.sqrt(n))):
if not factors[i]:
if n%i == 0:
factors[i] = True
factors[n/i] = True
for i, is_factor in enumerate(factors[1:], 1):
if is_factor:
ans.append(i)
ans.append(n)
return ans
ans = get_all_factors(60)
print [x for x in ans]