【问题标题】:How to find and print the prime factorization of a positive integer? [duplicate]如何找到并打印正整数的素数分解? [复制]
【发布时间】:2021-05-14 18:52:06
【问题描述】:
""""
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)

以上是我对这个问题的尝试。我试图先找到这些因素,然后确定它们是否是素数。我非常坚持这一点,如果有任何帮助或建议,我将不胜感激!

【问题讨论】:

  • 我不想使用内置的 Python 算法。我正在尝试制作自己的函数来打印字符串。
  • 欢迎来到 Stack Overflow。请编辑您的问题以澄清:您的算法的哪些部分不起作用以及您希望得到什么问题的回答:为什么您的特定代码不起作用,或者如何计算一般的素数分解。另请参阅stackoverflow.com/help/how-to-ask

标签: python math


【解决方案1】:

尝试编写此算法。不需要对素数进行测试,但对于具有非常大素因数的数字效率不高。

  1. 令 f = 2
  2. 将 f 的商和余数计算为 n。
  3. 如果没有余数,保存 f 并让 n = 商
  4. 如果有余数,则递增 f
  5. 重复 2-4 直到 n == 1。
  6. 返回保存的因子。

计算质因数 1-10,000 大约需要 2 秒,但接下来的 10,001 到 20,000 大约需要 5.5 秒。从那里开始变得更糟,但你会寻找优化。

【讨论】:

    猜你喜欢
    • 2021-05-14
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 2021-05-14
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多