Project Euler Problem 3 - Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
首先将给定n不断除以2,然后可只考虑奇因子
求出小于sqrt(n)的最大的n的奇因子,然后递归求解
Python代码:
from math import sqrt
from math import trunc
from time import clock
nb = 600851475143
def g(n):
""" n is odd """
a = trunc(sqrt(n))
if(a % 2 == 0):
a -= 1
while(n % a != 0):
a -= 2
if(a == 1):
return n
b = g(n/a)
if(b >= a):
return b
return max(g(a), b)
def f(n):
while(n % 2 == 0):
n /= 2
if(n == 1):
return 2
return g(n)
t = 10
s = clock()
for i in range(t):
r = f(nb)
e = clock()
print r, (e-s)/t # 0.06
复杂度?
posted on 2012-12-23 11:28 ZeroSnake0 阅读(142) 评论(0) 收藏 举报
浙公网安备 33010602011771号