def prime_factors(n):
sqrt_n = int(n**0.5)
result = []
if n == 1: return result
while n%2 == 0: # check for divisor = 2
result.append(2)
n /= 2
while n%3 == 0: # check for divisor = 3
result.append(3)
n /= 3
div = 5 # start with divisor = 6k-1 with k = 1
while div <= sqrt_n:
if n == 1: break
changed = n%div == 0
while n%div == 0: # check for i = 6k-1
result.append(div)
n /= div
div += 2 # proceed to 6k+1 = 6k-1 + 2
if not changed: changed = n%div == 0
while n%div == 0: # check for i = 6k+1
result.append(div)
n /= div
div += 4 # proceed to 6(k+1)-1 = 6k+5 = 6k+1 + 4
if changed: sqrt_n = int(n**0.5)
if n != 1: result.append(n)
return result
def largest_prime_factor(n):
if n == 1: return None
m = int(n**0.5)
while n%2 == 0: n /= 2
if n == 1: return 2
while n%3 == 0: n /= 3
if n == 1: return 3
i = 5
while i <= m:
changed = n%i == 0
while n%i == 0: n /= i
if n == 1: return i
i += 2
if not changed: changed = n%i == 0
while n%i == 0: n /= i
if n == 1: return i
i += 4
if changed: m = int(n**0.5)
if n != 1: return n
if __name__ == '__main__':
print prime_factors(600851475143)
print largest_prime_factor(600851475143)
ZGVmIHByaW1lX2ZhY3RvcnMobik6CiAgICBzcXJ0X24gPSBpbnQobioqMC41KQogICAgcmVzdWx0ID0gW10KICAgIGlmIG4gPT0gMTogcmV0dXJuIHJlc3VsdAogICAgd2hpbGUgbiUyID09IDA6ICAjIGNoZWNrIGZvciBkaXZpc29yID0gMgogICAgICAgIHJlc3VsdC5hcHBlbmQoMikKICAgICAgICBuIC89IDIgCiAgICB3aGlsZSBuJTMgPT0gMDogICMgY2hlY2sgZm9yIGRpdmlzb3IgPSAzCiAgICAgICAgcmVzdWx0LmFwcGVuZCgzKQogICAgICAgIG4gLz0gMwogICAgZGl2ID0gNSAgIyBzdGFydCB3aXRoIGRpdmlzb3IgPSA2ay0xIHdpdGggayA9IDEKICAgIHdoaWxlIGRpdiA8PSBzcXJ0X246CiAgICAgICAgaWYgbiA9PSAxOiBicmVhawogICAgICAgI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aQogICAgICAgIGlmIG4gPT0gMTogcmV0dXJuIGkKICAgICAgICBpICs9IDQKICAgICAgICBpZiBjaGFuZ2VkOiBtID0gaW50KG4qKjAuNSkKICAgIGlmIG4gIT0gMTogcmV0dXJuIG4KICAgIAogICAgCmlmIF9fbmFtZV9fID09ICdfX21haW5fXyc6CiAgICBwcmludCBwcmltZV9mYWN0b3JzKDYwMDg1MTQ3NTE0MykKICAgIHByaW50IGxhcmdlc3RfcHJpbWVfZmFjdG9yKDYwMDg1MTQ3NTE0Myk=