【问题标题】:Finding prime factors of a number求一个数的质因数
【发布时间】:2014-07-16 16:07:17
【问题描述】:

我试图找到 13195 的最大素数:

def problem3():
    divisors = []
    primes = []
    num = 13195
    for a in range(2, num):
        if num % a == 0:
            divisors.append(a)
    print divisors #This is the list of all divisors of the number
    // At this point divisors looks like:
    // [5, 7, 13, 29, 35, 65, 91, 145, 203, 377, 455, 1015, 1885, 2639]

    print ""
    primes = divisors
    for elements in divisors:
        for a in range(2,elements):
            if elements % a == 0:
                primes.remove(elements)
                print divisors
                break
    print primes

这是我得到的输出:

[5, 7, 13, 29, 65, 145, 377, 1015, 2639]

所以它对前四个素数效果很好,但是一旦它开始删除不是素数的数字,代码似乎会跳过检查除数列表中的下一个元素,并继续前进。为什么会这样?

【问题讨论】:

    标签: python prime-factoring


    【解决方案1】:

    重要的一行是:

    primes = divisors
    

    这不会复制列表 - primesdivisors 是同一个列表

    所以当你这样做时

    primes.remove(elements)
    

    同理:

    divisors.remove(elements)
    

    通过元素的迭代搞砸了,这就是它似乎跳过的原因。

    【讨论】:

    • 谢谢!完美运行!
    【解决方案2】:

    它跳过了下一个元素,因为一旦你删除了一个元素,后面的每个元素的索引都会减少一个。我会尝试在primes.remove(elements) 之后减少a

    【讨论】:

      【解决方案3】:

      问题是您正在从列表中删除同时被迭代的元素。它会破坏迭代。

      你可以这样做

      for elements in divisors:
          isPrime = True
          for a in range(2,int(math.sqrt(elements) + 1)):
              if elements % a == 0:
                  isPrime = False
                  break
          if isPrime:
              primes.append(elements)
      print primes
      

      【讨论】:

        猜你喜欢
        • 2013-07-06
        • 2016-03-17
        • 2021-03-30
        • 2017-02-25
        • 2019-10-21
        • 1970-01-01
        • 2020-09-04
        • 1970-01-01
        • 2019-04-26
        相关资源
        最近更新 更多