函数,用于打印任意数的素因子分解/Python

2024-05-16 13:42:13 发布

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

我正在寻找帮助编写一个函数,该函数接受一个正整数n作为输入,并将其素因子分解打印到屏幕上。输出应该将这些因子聚集到一个字符串中,这样像prime_factorization(60)这样的调用的结果将是将字符串“60 = 2 x 2 x 3 x 5”打印到屏幕上。以下是我到目前为止的情况。 更新:我取得了进展,并找到了如何找到素因式分解。但是,我仍然需要帮助以上面提到的正确方式打印它

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

请注意,我正在尝试打印它,因此如果输入为60,则输出为“60=2x2x3x5”


Tags: 函数字符串input屏幕is方式情况math
3条回答

下面是一种使用f字符串的方法。此外,您需要进行整数除法(带//),以避免答案中出现浮点数

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

def prime_factorization(n):
    n_copy = n
    prime_list = []
    while (n % 2) == 0:
        prime_list.append(2)
        # Turn n into odd number
        n = n // 2

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

    if (n > 2):
        prime_list.append(n)

    print(f'{n_copy} =', end = ' ')
    for factor in prime_list[:-1]:
        print (f'{factor} x', end=' ' )
    print(prime_list[-1])


prime_factorization(60)
#output: 60 = 2 x 2 x 3 x 5

使用列表存储所有因素,然后以所需格式将它们作为字符串一起打印

import math
def prime_factorization(n):
    factors = []  # to store factors
    while (n % 2) == 0:
        factors.append(2)
    
        # Turn n into odd number 
        n = n / 2

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

    if (n > 2):
        factors.append(n)

    print(" x ".join(str(i) for i in factors))  # to get the required string
    

prime_factorization(60)

您应该始终将计算与表示分开。您可以将函数构建为一个生成器,它通过增加除数(2,然后是赔率)来除数。当您找到一个合适的,输出它,并继续与结果的划分。这只会产生主要因素

然后使用该函数获取要打印的数据,而不是尝试混合打印和格式化

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

输出:

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

60 = 2 x 2 x 3 x 5

相关问题 更多 >