I am trying to get better at problem solving, so I am going through challenges on Project Euler.
Problem:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
My solution:
My approach to this was the following process:
Get all factors of the number
Identify prime factors by looping from 1 up to each factor. If the factor MOD the numbers going up is equal to 0 and the number is not 1 or the number itself, then it is not a prime. Then another for loop goes through each factor again and checks if it is not in the not primes list, hence making it a prime.
The last item in the primes list gives the biggest prime number
Code:
def get_factors(n):
factors = []
for i in range(1,n+1):
if n % i == 0:
factors.append(i)
return factors
def get_prime_factors(factors):
print(factors)
primes = []
not_primes = [1]
for i in range(len(factors)):
for k in range(1,factors[i]+1):
if factors[i] % k == 0 and factors[i] !=1 and k!=1 and k!=factors[i]:
not_primes.append(factors[i])
for i in factors:
if i not in not_primes:
primes.append(i)
return primes
def biggest_prime(primes):
biggest = primes[-1]
print(biggest)
factors = get_factors(600851475143)
primes = get_prime_factors(factors)
biggest_prime(primes)
Problems with my solution:
It seems like it is too overcomplicated, which is why it can only handle small numbers. The program did not finish executing for the number 600851475143.
What is specifically making my solution so inefficient, is it because I am using too many loops? How can I make it efficient?