Skip to content

Instantly share code, notes, and snippets.

@OskarSigvardsson
Created September 28, 2014 11:44
Show Gist options
  • Save OskarSigvardsson/9501f3d4b783b6801de2 to your computer and use it in GitHub Desktop.
Save OskarSigvardsson/9501f3d4b783b6801de2 to your computer and use it in GitHub Desktop.
def factors(n):
factors = []
# This loop weeds out any factors of 2 that are in the number
while n % 2 == 0:
factors.append(2)
n //= 2
# This variable holds the divisor that we're testing
d = 3
while d*d <= n: # Keep looping while d <= sqrt(n)
while n % d == 0: # Weed out factors of d
factors.append(d) # (remember, if n % d == 0, then d
n //= d # is guaranteed to be a prime in this case)
d += 2 # Find the next factor
# If n is not 1 at this point, then n is a prime factor
if n != 1:
factors.append(n)
return factors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment