如何在 python 中表示因子分解的多重性

how to represent multiplicty of prime factor in factorization in python

我编写了这个函数 factorization(n)... 如下所示

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

如果你写这个 分解(180)= [2,2,3,3,5] 但我想打印这种格式: 180 = 2^2 x 3^2 x 5

但我做不到。 我认为 'list counting' 很有用,但我不知道如何正确使用它每个因素的数量,并格式化它。

您可以使用collections.Counter:https://docs.python.org/3/library/collections.html#collections.Counter

from collections import Counter

counts = Counter(factorization(180))
counts[2]
counts[3]

使用原版 python 和一些格式:

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)

打印:

2^2*3^2*5