Search code examples
pythonprime-factoring

why doesn't my code seemingly work with odd numbers


I am trying to write code that will decompose a number into its prime factorization. It works so far for even numbers, but when I try an odd number it gets stuck. I don't know why that happens. I don't get an error it just stops doing anything.

The code:

priemwaarde = 100
priemgetallen = []
nonpriemgetallen = []
for x in range(2,priemwaarde):
    prime = True
    for i in range(2,x):
        if x % i  == 0:
            prime = False
    if prime == False:
        nonpriemgetallen.append(x)
    else:
        priemgetallen.append(x)

def PriemFactoren(getal):
    factoren = []
    a = getal
    while a not in priemgetallen:
        for priem in priemgetallen:
            if a % priem == 0:
                factoren.append(priem)
                a = a / priem
    a = int(a)
    if getal not in priemgetallen:
        factoren.append(a)
    return factoren
print(PriemFactoren(56))
print(PriemFactoren(55))

Solution

  • If you add a print statement or a debug breakpoint within your while loop, you'll find that it's stuck because the value of a is eventually 1, and it's not able to find it in priemgetallen.

    A quick fix to break out of the infinite loop that comes to mind is to just add it to the list:

    priemgetallen.append(1)
    

    I suppose another option is to handle that value explicitly, so something like this should also break the infinite loop:

    def PriemFactoren(getal):
        factoren = []
        a = getal
        while a not in priemgetallen:
            #### Added lines
            if a == 1:
                break
            #### End
            for priem in priemgetallen:
                if a % priem == 0:
                    factoren.append(priem)
                    a = a / priem
        a = int(a)
        if getal not in priemgetallen:
            factoren.append(a)
        return factoren