projecteuler网站第三题解法:Get the largest prime factor of a number

原题酱紫的:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

 

大脑短路,直接写个简单的遍历,从600851475143/2 到2,然后检查哪一个是质数,结果程序跑了半天还在跑。

 

关于质数因子的知识没啥记忆,在网上搜索了一下,有位同学给出代码,正好是我用的Python:

这是原地址:http://www.nickpeters.net/2009/08/02/find-the-largest-prime-factor/

 

他的代码是酱紫的:

n = 600851475143 # Find the largest prime factor of this
div = [x for x in range(2,int(math.sqrt(n))) if n % x == 0] # Get all factors
i, j = 0, len(div) - 1
while j > i: # Determine which one of the factors is the largest prime
# This number is composite, go to the next largest factor
if div[j] % div[i] == 0: i,j = 0,j-1
# See if the next number at the beginning of the list divides the current number
else: i += 1
print div[j] # Print out the largest prime factor

但是显然没考虑完整,因子没取完,只取了一半,例如n=14时,他的答案就是2,正确答案当然应该是7;
后半部分代码,我在脑子里自己反证了了一把,确定无误,朋友们有空自己想一下。
我修改后的代码如下:
(多加了一些集合限制)

import math
n = 600851475143
div = []
if n % 2 == 0: div.append(2)
div += [x for x in range(3, int(math.sqrt(n))) if (n % x == 0 and x % 2 != 0)]
divTemp = [n/x for x in div if n/x%2 != 0]
div += divTemp
i, j = 0, len(div) - 1
while j > i:
if div[j] % div[i] == 0: i,j = 0,j-1
else: i += 1

print div[j]


另附:数学知识一定要多复习,这么个简单程序也让我写了半天, 非常不爽 。。。。。。。。。。。。

你可能感兴趣的:(Python)