pythonpython-requestsintegerformatfactorization

how to represent multiplicty of prime factor in factorization in python


I code this function factorization(n)... like below

def factorization(n):
    factor=[]
    for i in range(2,n+1):
        while n % i == 0:
            n = n/i
            factor.append(i)
        print(factor)

and if you write this factorization(180) = [2,2,3,3,5] but i want to print this format: 180 = 2^2 x 3^2 x 5

but i cant make it. i think 'list counting' is useful but i don't know how to use it correctly the number of each factor, and format it.


Solution

  • Using vanilla python & some formatting:

    def factorization(n):
        factor = []
        for i in range(2, n + 1):
            while n % i == 0:
                n = n / i
                factor.append(i)
        print('*'.join(f'{n}' + (f'^{factor.count(n)}' if factor.count(n) > 1 else '') for n in set(factor)))
    
    
    factorization(180)
    

    Prints:

    2^2*3^2*5