I'm trying to solve a problem from the Project Euler archive: https://projecteuler.net/problem=3
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?
I tried solving for 13195 first. My original idea was to create a list with all the prime numbers lower than the given number. I used the Sieve of Erathostenes algorithm to do this. Then, using a for loop I iterated through all those prime numbers adding the ones that are factors of the given number to a separate list. I sorted the list and printed the largest factor. When I ran the script I got one extra number in the factors list that was not a factor of the given number.
for num = 13915
the output should have been [13, 29, 5, 7] but instead I got [13, 29, 377, 5, 7]
I wasn't able to figure out where 377 came from. I'm aware my solution is not the most efficient one but I tried solving this problem myself. So my questions are:
Where did 377 come from? Can you suggest a more efficient way to solve this problem?
I apologize for any inconveniences as I'm new to problem solving in Python.
primes = []
num = 13195
factors = []
for i in range(1, num + 1):
#sieve of erathostenes
if i % 2 != 0 and i % 3 != 0 and i % 5 != 0 and i % 7 != 0 and i != 1:
primes.append(i)
if num >= 10:
primes.append(2)
primes.append(3)
primes.append(5)
primes.append(7)
sorted(primes)
for i in range(len(primes)):
prime = primes[i]
if num % prime == 0:
factors.append(primes[i])
print(factors)
factors.sort()
print(factors[len(factors) - 1])