""""
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)以上是我对这个问题的尝试。我试着先找到因子,然后再确定它们是否是质数。我非常坚持这一点,并感谢任何帮助或建议!
发布于 2021-02-11 10:03:38
这是一个使用两种广为人知的算法及其在Python中对数>0的实现的解决方案:Sieve of Ertosthenes: Prime numbers和Factors 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 5https://stackoverflow.com/questions/66147166
复制相似问题