【问题标题】:Function that prints prime factorization of any number / Python打印任何数字的素数分解的函数/ Python
【发布时间】:2021-05-14 19:56:42
【问题描述】:

我正在寻求帮助编写一个函数,该函数将正整数 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 = 2 x 2 x 3 x 5”

【问题讨论】:

  • My post here 展示了一种使用 sympy 库的方法,除非您想自己动手。
  • 你试过这样打印吗?你遇到了什么问题?
  • 程序打印以下内容:2 2 3 5.0 我不知道如何让它打印这样的字符串:'60 = 2 x 2 x 3 x 5'
  • 你知道如何使用列表吗?你知道如何操作字符串吗?

标签: python python-3.x jupyter-notebook jupyter


【解决方案1】:

您应该始终将计算与表示分开。您可以将函数构建为生成器,通过增加除数(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

【讨论】:

    【解决方案2】:

    这是一种使用 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
    

    【讨论】:

      【解决方案3】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-06
        • 1970-01-01
        • 1970-01-01
        • 2021-05-14
        • 1970-01-01
        • 1970-01-01
        • 2021-05-14
        相关资源
        最近更新 更多