0
""""
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)

Above is my attempt at the problem. I tried to find the factors first and then determine if they are prime. I'm extremely stuck on this and would appreciate any help or suggestions!

Stiff
  • 47
  • 7
  • I'm looking to write an entirely new function to figure this out, opposed to using pre-made Python algorithms. – Stiff Feb 11 '21 at 02:24

1 Answers1

0

This is a solution using two widely known algorithms and their implementation in Python for a number > 0: Sieve of Ertosthenes: Prime numbers and 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)

Output:

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
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43