I'm currently trying to solve Project Euler problem 3 using python, which is trying to find the largest prime factor of a number. The method I'm using is essentially brute forcing my way through each integer less than the integer in question, checking if it's a factor of said integer, and then checking if it is prime. However, for some reason, my code doesn't seem to be working.
I've tried to use create a function which goes through each integer (i) less than a given integer (n), and if i is divisible by n, the function then proceeds to check if i is a prime number by going through every integer less or equal to i (x). if x is a factor of i, then the value is added to a zero-integer defined as (a). After that, if a ends up adding to equal i + 1, then that means the factor is prime, since the only numbers divisible were itself and 1. The code is as below:
def primefactor(n):
for i in range(1, n+1): #goes through each integer less than n
if n % i == 0: #checks if integer is a factor
for x in range(1, i+1): #another loop to check if the factor is prime
a = 0
primenumbers = []
if i % x == 0:
a += x
if a == i + 1:
primenumbers.append(i)
print(primenumbers)
primefactor(13195)
What i expected the output to be was for it to print a list of all of the prime factors of the number, in this case, [5, 7, 13, 29]
, but instead, all I got was an empty list, []