Search code examples
pythonprime-factoring

Prime factor decomposition not working for numbers with repeated factors


In this code, the user has to input an interval, and the program has to calculate the prime factor decomposition for each number in this interval.

However, I am unable to print the correct prime factor decomposition for numbers that have repeated factors, such as 4, 8 and 9.

I tried to use a while loop, but I am unable to use it correctly and my code just runs nonstop.

Problem requirement: Find the prime factorization of all integers in a given interval [a,b].

Expected output for range(3,10):

3=3
4=2*2
5=5
6=2*3
7=7
8=2*2*2
9=3*3
10=2*5

My code:

a, b = map(int, input().split())
j = [] #list for prime numbers
lst = [] #list for factors for numbers in range(a,b)


# prime numbers
for number in range(2, b+1):
    for i in range(2, number):
        if number % i == 0:
            break
    else:
        j.append(number)

#factors
for c in range(a, b+1):
    lst = []
    for i in j:
        k = c % i
        if k == 0:
            lst.append(i)

    print(f'{c}=', end='')
    print(*lst, sep='*')

My Code Output for range (3,10):

3=3
4=2
5=5
6=2*3
7=7
8=2
9=3
10=2*5

I appreciate any feedback I can get, thank you!


Solution

  • Close. Instead of checking c % i just once, you have to loop until that is no longer 0.

    #factors
    for c in range(a, b+1):
        print(f'{c}=', end='')
        lst = []
        for i in j:
            while i <= c and c % i == 0:
                c //= i
                lst.append(i)
    
        print(*lst, sep='*')
    

    Note that I had to move the print of c to the top of the loop, because I'm modifying c within the loop. I didn't notice that until I did a test run.