http://projecteuler.net/problem=3
最开始自己的方法很麻烦,每次运行,都会卡。经过xw_y_am童鞋的点拨:http://tieba.baidu.com/p/1558545720 自己也做出来啦 在此对xw_y_am表示感谢。
#! /usr/bin/env python
# Filename: po3.py
from math import floor
from math import sqrt
def isprimer(num):
if num < 2 or num % 2 == 0 and num != 2:
return False
end = floor(sqrt(num)) + 1
fac = 3
while fac < end:
if num % fac == 0:
return False
fac += 2
return True
def main():
num = 600851475143L
fac_small = 1
fac_big = 0
step = 1 if num % 2 == 0 else 2
end = floor(sqrt(num)) + 1
max_primer_fac = 0
while fac_small < end:
if num % fac_small == 0:
fac_big = num / fac_small
if isprimer(fac_big):
max_primer_fac = fac_big
break
elif isprimer(fac_small):
max_primer_fac = fac_small
fac_small += step
if max_primer_fac != 0:
print("%d" % (max_primer_fac))
if __name__ == '__main__':
main()
第一版:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Filename: _3.py
from math import sqrt
from math import floor
def isprimer(num):
fac_max = floor(sqrt(num)) + 1
for fac in range(2, fac_max):
if num % fac == 0: return False
return True
def primer(lim):
for n in range(3, lim, 2):
if isprimer(n):
yield n
def main():
num = 600851475143
primer_fac = list(primer(num))
primer_fac_rev = primer_fac[-1::-1]
for pf in primer_fac_rev:
if num % pf == 0:
print("the largest prime factor of %d is %d" % (num, pf))
break
if __name__ == '__main__':
main()