So I am essentially a complete newbie to programming, and have been attempting to learn Python by completing the Project Euler problems. I haven't gotten very far, and this is my code for problem #3 :
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?
Although my solution works, I'd like to know how I can improve.
primes = [2]
factors = []
def isPrime(x):
a = 1
if x == 1:
return False
while a < x:
a += 1
if x % a == 0 and a != x and a != 1:
return False
break
return True
def generatePrime():
a = primes[-1]+1
while isPrime(a) == False:
a += 1
primes.append(a)
def primeFactor(x):
a = primes[-1]
while a <= x:
if x % a == 0:
factors.append(a)
x /= a
generatePrime()
a = primes[-1]
primeFactor(input("Enter the number: "))
print("The prime factors are: " + str(factors) + "\nThe largest prime factor is: " + str(sorted(factors)[-1]))
while a < x:
withwhile a < math.sqrt(x):
You can also check whether x is even and > 2, in that case it is not a prime, also google for 'prime sieve'. \$\endgroup\$