Problem 3: Largest prime factor
Do you remember how to do prime factorization?
Problem
πThe prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
π Key Idea
prime factorization algorithm into code
n = 600851475143
def is_prime(n):
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i is 0:
return False
return True
max = 0
for i in range(3, n, 2):
if i % 3 is 0 or i % 5 is 0 or i % 7 is 0:
continue
if n % i is 0:
if is_prime(i):
max = i
print(max)
Why did I get it wrong?
I forgot how to do prime factorization. π
n = 600851475143
max = 0
i = 2
while n > 1:
if n % i is 0: # prime factor found
n = n // i
if i > max:
max = i
i = 2
continue
i += 1
print(max)
Note: We donβt have to check whether
i
is prime or not, because we are iterating i
from 2, therefore the factor will always be the smallest prime factor for the current n
. And also, we can skip the if i > max
check because the last factor that divides n
to 1 will be the biggest factor.
Important: In Python,
0
and 0.0
is different. Evaluating 0 is 0.0
will return False
.