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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.