I am unable to understand the following block of code which I came across this site itself. It creates a function to find out the largest prime factor of a given number. It is given below:
def prime_factors(n):
"""Returns all the prime factors of a positive integer"""
factors = []
d = 2
while n > 1:
while n % d == 0:
factors.append(d)
n /= d
d = d + 1
return factors
pfs = prime_factors(1000)
largest_prime_factor = max(pfs) # The largest element in the prime
My doubt is that the function prime_factors(n)
would return the factors of n
and not the prime factors, since the while loop is only checking if d
is a factor of n
and not if it is also a prime as it should be.
Please point out if I'm wrong and also the reasoning behind your logic. Furthermore, if I'm correct, then kindly provide a suitable block of code and the logic behind it in simple terms. Try to keep the code as simple as possible.