How I add to a list same number multiple times by count?

73 Views Asked by At

I've got 2 problems here.

my first problem is that the code shows me only one time a factor even though it's multiple x times by the same factor. I don't know how to add it to the factor list.

Another problem is I'm not sure in print - how the sep works and how can I write "*" only between elements of factor list.

I can't use any import functions here (intertools, maths etc.)

Please help me.

def factorize(n):
    prvocisla = []
    faktor = []
    #prime numbers
    for num in range(1, 2000):
       if num > 1:
           for i in range(2, num):
               if (num % i) == 0:
                   break
           else:
               prvocisla.append(num)
    count = 0           
    for i in prvocisla:
        if n % i == 0:
            count += 1
            faktor.append(i)
    print(n, " =", *faktor , sep=' *', end='\n')
    
factorize(360)

My result:
360 * = *2 *3 *5

The right result:
360 = 2 * 2 * 2 * 3 * 3 * 5

I try the count function with adding same factor to the list "count times" but it shows me an Error.

1

There are 1 best solutions below

0
Lorenzo Zorri On

The problem is that in your second 'for' loop you evaluate if there is a prime number in your number, but not how many times it is present.

To do this you need to repeat the cycle every time you find a prime number and divide the initial number by the prime number. this way you will get to 1 and get all the factors in the array.

Here the right code:

def factorize(n):
    prvocisla = []
    faktor = []
    #prime numbers
    for num in range(1, 2000):
        if num > 1:
            for i in range(2, num):
                if (num % i) == 0:
                    break
            else:
                prvocisla.append(num)
    count = 0  

    t = n    # <-- a temporary variable which get n value
    while t>1:
        for i in prvocisla:
            if t % i == 0:
                count += 1
                faktor.append(i)
                t = t/i    <-- divide t every time you find a factor
                break

    print(f"{n!s} = {' * '.join(str(k) for k in faktor)}")

factorize(360)

For the print I use the @CreepyRaccoon suggestion.