Function names
n
and eq
are very unclear names, unless they clearly correspond to a referenced formula. eq
usually stands for "equals" or "equation", and it's not clear what "equals" would do for one input.
Input handling
I assume you have a consistent way to handle negative numbers. You can simply output -1 as a factor, test for 0, and then only consider positive integers. This would reduce the negative number and zero checks.
Trial Division Algorithm
I think a for loop testing divisors from 2 to n instead of unbounded incrementing is easier to understand. A simple optimization is to divide out 2s and then odds. In fact, you need to only try dividing out primes. (Why is this true?) In this way, using a sieve to get a list of primes and only trying dividing those will be much faster for large inputs (prime number theorem). By the way, the largest factor to try division is sqrt(n); if n leftover after dividing is not 1 then that is the largest prime factor. (Why is this true?) This cuts down the worst-case number of checks from O(n) to O(sqrt n).
Here is python / pseudocode that factors a number into a dictionary of its prime factorization (similar to sympy's factorint
):
def factor(n):
assert n > 0 # only handle positive integer input
factors = Counter()
for d in range(2, int(n**0.5)+1n): # maybe loss of precision for huge inputs
if d * d > n: break # d up to sqrt(n)
while n % d == 0:
n //= d
factors[d] += 1
if n > 1:
factors[n] += 1
return factors