Matthew
Matthew

Reputation: 63

Prime Factorization in Python

I found this piece of code online and it basically functions by factorizing a given number into its prime factors and lists them.

def primefactors(x):
factorlist=[]
loop=2
while loop<=x:
    if x%loop==0:
        x/=loop
        factorlist.append(loop)
    else:
        loop+=1
return factorlist

Now I understand this code works in general. It takes the number 'loop' starting from 2 and looks to see if it can be divided into the number x. If yes, then it adds to the list and if not, 1 is added and the process is repeated. However I am unsure of this part.

x/=loop

What does this operator '/=' do and how does it prevent larger non prime numbers from appearing in the list?

Thanks for all the help

Upvotes: 0

Views: 126

Answers (2)

happydave
happydave

Reputation: 7187

x /= loop is equivalent to x = x / loop.

Since you are dividing x by loop until loop is no longer a factor of x, by the time you get to any composite number, you'll have already divided out all of its prime factors, so the composite number will not be a factor of the current value of x.

Upvotes: 2

PyNico
PyNico

Reputation: 695

/= Divide AND

It divides left operand with the right operand and assign the result to left operand

example : c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a

Upvotes: 0

Related Questions