Q: Given A,B and K. Find all the numbers between A and B(inclusive) that have K DISTINCT prime factors. Here's what I've done.I've implemented the Sieve of Eratosthenes and computed all the primes till the upper bound of A,B. Then I proceed to find which of these primes is a factor of the numbers between A and B. If the number of distinct primes is equal to K, I increment count. The problem I'm running into is that of time. Even after implementing the sieve, it takes 10 seconds to compute the answer to 2,10000,1 (The numbers between 2 and 100000 that have 1 distinct prime factor) here's my code
import math
#Sieve of erastothenes
def sieve(n):
numbers=range(0,n+1)
for i in range(2,int(math.ceil(n**0.5))):
if(numbers[i]):
for j in range(i*i,n+1,i):
numbers[j]=0
#removing 0 and 1 and returning a list
numbers.remove(1)
prime_numbers=set(numbers)
prime_numbers.remove(0)
primes=list(prime_numbers)
primes.sort()
return primes
prime_numbers=[]
prime_numbers=sieve(100000)
#print prime_numbers
def no_of_distinct_prime_factors(n):
count=0
flag=0
#print prime_numbers
for i in prime_numbers:
#print i
if i>n:
break
if n%i==0:
count+=1
n=n/i
return count
t=raw_input()
t=int(t)
foo=[]
split=[]
for i in range (0,t):
raw=raw_input()
foo=raw.split(" ")
split.append(foo)
for i in range(0,t):
count=0
for k in range(int(split[i][0]),int(split[i][1])+1):
if no_of_distinct_prime_factors(k)==int(split[i][2]):
count+=1
print count
Any tips on how to optimize it further?