如何编写一个接受正整数并打印其素因子分解的函数?

2024-05-16 16:11:23 发布

您现在位置:Python中文网/ 问答频道 /正文

""""
A function that takes a positive integer n as input and prints its prime factorization to 
the screen. 
Gather the factors together into a single string, so that the results of a call like
(60) would be to print the string “60 = 2 x 2 x 3 x 5” to the screen.
Looking for a way to build prime_factorization such that every factor you find will be prime 
automatically.
"""
def prime_factorization(n):
    results = 0
    for i in range(1, n + 1):
        if (n % i) == 0:
            prime = True
            for x in range(2, i):
                if (i % x) == 0:
                    prime = False
            if prime:
                results = results + i
            return results

prime_factorization(60)

以上是我对这个问题的尝试。我试图先找到这些因子,然后确定它们是否为素数。我非常坚持这一点,并将感谢任何帮助或建议


Tags: thetoinforstringifthatrange
1条回答
网友
1楼 · 发布于 2024-05-16 16:11:23

这是一个解决方案,使用了两种广为人知的算法及其在Python中对数字>;0Sieve of Ertosthenes: Prime numbersFactors of a number

from operator import mul
from functools import reduce
from itertools import combinations_with_replacement as cwr


def factors(n):
    return set(
        reduce(
            list.__add__,
            ([i, n // i] for i in range(1, int(n**0.5) + 1) if n % i == 0)
        )
    )


def primes_sieve(limit):
    a = [True] * limit
    a[0] = a[1] = False

    for (i, isprime) in enumerate(a):
        if isprime:
            yield i
            for n in range(i * i, limit, i):
                a[n] = False


def prime_factorization(number):
    fcts = factors(number)
    primes = set(primes_sieve(number)) if number > 2 else set()
    intersection = fcts & primes
    if not intersection:
        return f'{num} = {num} x 1'
    length = len(intersection)
    while True:
        for elm in cwr(intersection, length):
            val = reduce(lambda x, y: mul(x, y), elm)
            if val == number:
                return f"{number} = {' x '.join(str(k) for k in elm)}"
        length += 1


numbers = [1, 2, 3, 4, 7, 12, 26, 60]
for num in numbers:
    result = prime_factorization(num)
    print(result)

输出:

1 = 1 x 1
2 = 2 x 1
3 = 3 x 1
4 = 2 x 2
7 = 7 x 1
12 = 2 x 2 x 3
26 = 2 x 13
60 = 2 x 2 x 3 x 5

相关问题 更多 >