Project Euler third question

Tags (separated by spaces): Euler blog


Largest prime factor

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

What is the largest prime factor of the number 600851475143 ?

Meaning of the questions is very simple, find the largest prime factor of a number of prime factor 13195 has 5,7,13,29 largest of which is 29, seeking 600 851 475 143 largest prime factor.

The first reaction is seeking 600851475143 all factors, which then find the largest prime number.

ans = []
n = 600851475143
max = int(n**0.5)
for x in range(2, max):
    if n%x == 0:
        ans.append(x)

print(ans)

ans = [71, 839, 1471, 6857, 59569, 104441, 486847]

Find no factor accelerating skills, but above program already running very quickly, but a judge is not a prime number there are some acceleration techniques, a common筛素数法

筛素 number

Because multiple primes certainly not a prime number, so we can exclude it when multiples to find a prime number, such as seeking primes less than 100:

n = 100
L = list(range(2, n))
ans = set()
while L:
    x = L.pop(0)
    ans.add(x)
    i = 2
    while i*x < n:
        if i*x in L:
            L.remove(i*x)
        i += 1
print(ans)
ans = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}

It will weed out the composite number based on this idea, we can find a factor of 600 851 475 143,

ans = []
n = 600851475143
iter_max = int(n ** 0.5)
for num in range(2,iter_max):
    if n%num == 0:
        ans.append(num)
        n/=num
        while n%num == 0:
            n/=num # 保证n已被num除尽,此时n不会再有num*i的因数
print(ans)
ans = [71, 839, 1471, 6857]

The end result is 6857

Guess you like

Origin www.cnblogs.com/lepeCoder/p/10991575.html