Prime screening method -- SPOJ Problem 2 Prime Generator, -- spojprime
Prime number is also called a prime number. Apart from 1 and itself, it cannot be divided into other natural numbers. In other words, this number has no other factors except 1 and itself; otherwise, it is called the sum. The minimum prime number is 2.
It is easy to judge whether an integer N is a prime number and whether it can be divisible by an integer between 2 and sqrt (N.
def isPrime(n): if n%2==0: return False for i in xrange(3,int(math.sqrt(n)+1),2): if n%i==0: return False return True
However, it is obviously not a good idea to identify all the prime numbers between 1 and N. Since the sum can be divided into a series of products of prime numbers, the sum between 1 and N is a multiple of a prime number between 1 and sqrt (N). Excluding the sum, the remainder is the prime number:
import mathimport timeitdef findPrime(n): a=[True]*(n+1) a[0]=False a[1]=False for i in xrange(2,int(math.sqrt(n)+1)): if a[i]: k=i*i while k<=n: a[k]=False k=k+i if __name__=='__main__': t=timeit.Timer('findPrime(2000000)','from __main__ import findPrime') print t.timeit(1)
The algorithm starts from 2 to determine whether it is a prime number and removes a multiple of the prime number. When both 2 and I are determined, it is clear whether I + 1 is a prime number.
SPOJ Problem 2 Prime Generator requires finding the Prime number between n and m, where 1 <= m <= n <= 1000000000, n-m <= 100000.
In this case, creating a 1000000000-length sequence is a waste of space. You need to first find the prime number between 1 and sqrt (n), and then eliminate the multiples of these prime numbers between n and m:
import mathdef findPrime(n): a=[True]*(n+1) a[0]=False a[1]=False for i in xrange(2,int(math.sqrt(n)+1)): if a[i]: k=i*i while k<=n: a[k]=False k=k+i for i in xrange(2,n+1): if a[i]: yield idef findPrimeBySeed(n,m): if n==1: n=2 seed=findPrime(int(math.sqrt(m))) alist=[1]*(m-n+1) for prime in seed: if prime<n: k=(prime-n%prime)%prime else: k=2*prime-n while k<=m-n: alist[k]=False k+=prime for i in xrange(m-n+1): if alist[i]: print i+n if __name__=='__main__': line=int(raw_input()) for i in xrange(line): n,m=raw_input().split() findPrimeBySeed(int(n),int(m)) print