简体   繁体   English

在python中计算素因数

[英]Compute prime factors in python

I currently have a list containing numbers:我目前有一个包含数字的列表:

lst = [3,4,6]

and I'm trying to compute the prime factors of the numbers in the list where i obtain the output of我正在尝试计算列表中数字的素因数,在那里我获得了

3^1
2^2
2^1 x 3^1

Here's what i tried:这是我尝试过的:

def prime_factors(lst):
   for j in range(len(lst)):
       i = 2
       factors = []
       while i*i <= j:
           if j%i:
               i+=1
           else:
               j//= i
               factors.append(i)
       if j > 1:
           factors.append(j)
  return factors

but I'm getting [2] as the output.但我得到 [2] 作为输出。 Would appreciate some help on this.将不胜感激在这方面的一些帮助。

Well i did it from scratch , It uses a modification of the prime number sieve algorithm .好吧,我从头开始,它使用了质数筛算法的修改。

from math import sqrt
from collections import Counter
def prime_factors(lst):
    maximumnumber=max(lst)
    primesieve=[0]*(maximumnumber+1)
    primesieve[0]=1
    primesieve[1]=1
    #DOING PRIME NUMBER SIEVE
    for i in range(2,int(sqrt(maximumnumber))+1):
        if(primesieve[i]==0):
            for j in range(2*i,len(primesieve),i):
                primesieve[j]=i

    for j in range(len(lst)):
        num=lst[j]
        factors=[]
        #take each number(num) and divided it by a prime number (primesieve[num])
        #do it until you find no more prime factors for number
        while(primesieve[num]>0):

            factors.append(primesieve[num])
            num=num//primesieve[num]
        factors.append(num)
        yield Counter(factors)

for i in prime_factors([3,4,6]):
    print(i)

Output输出

Counter({3: 1})
Counter({2: 2})
Counter({2: 1, 3: 1})

Ill explain what i have done我会解释我做了什么

  1. Found prime numbers between the 0 and maximum element in the list using the prime number sieve algorithm , Link to a the algorithm , I just modified one part that algorithm that is instead of using a the primenumber array as boolean i used ,Integer to show which number it was divided with使用素数筛选算法在列表中的 0 和最大元素之间找到素数,链接到算法,我只是修改了该算法的一部分,而不是使用素数数组作为布尔值,整数来显示哪个它被除以的数字
  2. Iterate through the numbers and find all the prime factors遍历数字并找到所有质因数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM