Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that prints prime factorization of any number / Python

I'm looking for help writing a function that takes a positive integer n as input and prints its prime factorization to the screen. The output should gather the factors together into a single string so that the results of a call like prime_factorization(60) would be to print the string “60 = 2 x 2 x 3 x 5” to the screen. The following is what I have so far. UPDATE: I made progress and figured out how to find the prime factorization. However, I still need help printing it the correct way as mentioned above.

""""
Input is a positive integer n
Output is its prime factorization, computed as follows: 

"""
import math
def prime_factorization(n):

    while (n % 2) == 0:
        print(2)
    
        # Turn n into odd number 
        n = n / 2

    for i in range (3, int(math.sqrt(n)) + 1, 2):
    
        while (n % i) == 0:
            print(i)
            n = n / I

    if (n > 2):
        print(n)
    

prime_factorization(60)

Note that I am trying to print it so if the input is 60, the output reads " 60 = 2 x 2 x 3 x 5 "

like image 633
Stiff Avatar asked Aug 17 '26 10:08

Stiff


1 Answers

You should always separate computation from presentation. You can build the function as a generator that divides the number by increasing divisors (2 and then odds). When you find one that fits, output it and continue with the result of the division. This will only produce prime factors.

Then use that function to obtain the data to print rather than trying to mix in the printing and formatting.

def primeFactors(N):
    p,i = 2,1               # prime divisor and increment
    while p*p<=N:           # no need to go beyond √N 
        while N%p == 0:     # if is integer divisor
            yield p         # output prime divisor
            N //= p         # remove it from the number
        p,i = p+i,2         # advance to next potential divisor 2, 3, 5, ... 
    if N>1: yield N         # remaining value is a prime if not 1

output:

N=60
print(N,end=" = ")
print(*primeFactors(N),sep=" x ")

60 = 2 x 2 x 3 x 5
like image 147
Alain T. Avatar answered Aug 19 '26 16:08

Alain T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!