🛠️ToolsShed

质数检验与质因数分解

检验一个数是否为质数,并求其质因数分解。

显示以下范围内的质数

常见问题

代码实现

def prime_factors(n: int) -> dict[int, int]:
    """Return prime factorization as {prime: exponent} dict."""
    if n < 2:
        return {}
    factors = {}
    d = 2
    while d * d <= n:
        while n % d == 0:
            factors[d] = factors.get(d, 0) + 1
            n //= d
        d += 1
    if n > 1:
        factors[n] = factors.get(n, 0) + 1
    return factors

def format_factorization(n: int) -> str:
    factors = prime_factors(n)
    parts = [f"{p}^{e}" if e > 1 else str(p) for p, e in sorted(factors.items())]
    return " × ".join(parts)

print(prime_factors(360))         # {2: 3, 3: 2, 5: 1}
print(format_factorization(360))  # 2^3 × 3^2 × 5
print(format_factorization(97))   # 97  (prime itself)

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.