【问题标题】:Python - Integer Factorization into Primes [closed]Python - 将整数分解为素数 [关闭]
【发布时间】:2013-01-27 18:40:59
【问题描述】:

我写了一个整数分解函数,但在搞砸之后,我意识到它有几个数字的问题......

>>> pFactors(99) # it does work for numbers with multiple of one prime factor
[3, 3, 11]
>>> pFactors(999) # however, sometimes, it doesn't
[3, 37] # the actual prime factorization of 999 is [3, 3, 3, 37]. 
>>> pFactors(88)
[2, 11]
>>> pFactors(888)
[2, 3, 37]

我的代码有什么问题?

def pFactors(n):
   """Finds the prime factors of 'n'"""
   from primes import isPrime
   from math import sqrt
   pFact, limit, check, num = [], int(round(sqrt(n), 2)) + 1, 2, n
   if isPrime(n):
      return [n]
   for check in range(2, limit):
      if isPrime(check) and num % check == 0:
         pFact.append(check)
         num /= check
         if isPrime(num):
            pFact.append(num)
            break
   pFact = sorted(pFact)
   return pFact

【问题讨论】:

  • 每次分解数字都需要重新计算limit并重启循环。我会在这里推荐一种递归方法,而不是你的迭代方法。

标签: python prime-factoring


【解决方案1】:

修改如下:

def pFactors(n): 
        """Finds the prime factors of 'n'""" 
        from math import sqrt 
        pFact, limit, check, num = [], int(sqrt(n)) + 1, 2, n 
        if n == 1: return [1] 
        for check in range(2, limit): 
             while num % check == 0: 
                pFact.append(check) 
                num /= check 
        if num > 1: 
          pFact.append(num) 
        return pFact 

for i in range(1,1000):
        print pFactors(i)

虽然我喜欢你最初编写的代码,但有几点:

  1. 您不需要 isPrime。原因是任何在限制范围内除以 num 的素数也将是除以 num 的任何复合的最小除数,因此当您除掉这些素数时,您将防止它们组成的复合被发现为范围后面的除数,只剩下主要因素。

  2. 你不需要对数组进行排序,它已经通过check升序排序了。

  3. 添加的 while 循环确保只要重复因子继续除 num,就可以正确找到它们。

  4. 您可以使用同余过滤掉小于限制的所有数字的 2/3 作为除数进行检查,您知道怎么做吗?

上面结果的最后几行是:

[11, 89]
[2, 2, 5, 7, 7]
[3, 3, 109]
[2, 491]
[983]
[2, 2, 2, 3, 41]
[5, 197]
[2, 17, 29]
[3, 7, 47]
[2, 2, 13, 19]
[23, 43]
[2, 3, 3, 5, 11]
[991]
[2, 2, 2, 2, 2, 31]
[3, 331]
[2, 7, 71]
[5, 199]
[2, 2, 3, 83]
[997]
[2, 499]
[3, 3, 3, 37]

【讨论】:

  • 啊,while 循环修复了它。感谢您的建议和其他建议:)
  • 不客气。祝你好运!
  • 你可以通过计算重复因子得到一个很好的因子和指数表示;例如[[(x, p.count(x)) for x in set(p)] for p in [pFactors(1536000)]][0] 产生[(2, 12), (3, 1), (5, 3)],这意味着“2 的 12 次方乘以 3 的 1 次方乘以 5 的三次方。”
【解决方案2】:

在 999 示例中,将其除以 3 后,结果 (333) 也可除以 3,即得到 111,您也可以除以 3(得到 37)。 但是在您的代码中,您只需将其除一次 - 您需要做的是,一旦您找到一个可以除以您当前数字的素数,就是继续除以该数字,直到它不再可能为止。

【讨论】:

    猜你喜欢
    • 2021-05-24
    • 2020-04-14
    • 1970-01-01
    • 2021-06-30
    • 2013-11-28
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多