Search code examples
pythonpython-3.xprimessymbolic-mathprime-factoring

Way to express prime factors of a number


My task is to return the prime factors of an integer(n). My question is how do I express this in a mathematical expression for coding? I know that primes are numbers that are only divisible by 1 and itself but do not know how to put that in code.

I did however find this coding which works but I do not know why:

def primes(n):

    primfac = []
    d = 2
    while d*d <= n:
        while (n % d) == 0:
            primfac.append(d)  
            n //= d
        d += 1
    if n > 1:
       primfac.append(n)
    return primfac

Can someone explain to me why this coding works? Why is d chosen as 2 to start off instead of 1? Also why does he square d and check if it's equal to or less than n? and so on.


Solution

  • d Starts off at 2 because you would end up with an infinite list of 1s as factors as Tom Karzes mentions. The reason he squares d and checks if it is equal to n is because you only need to check up to the square root of the number for its factors and math.sqrt() is more computationally expensive than squaring as number. What it does is it checks if d us a factor of n until d reaches the square root of n. He then appends d because it has been checked to be a factor.

    Is there anything else you don't understand about the code?