Prime Generator

Input

The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.

Output

For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

Example

Input:
2
1 10
3 5

Output:
2
3
5
7

3
5

Code

from math import sqrt

def Primes(primes): # 生成筛子:2-sqrt(1,000,000,000)之间的所有素数
    for i in range(3,31622,2):
        isprime = True
        cap = sqrt(i)+1
        for j in primes:
            if (j >= cap):
                break
            if (i % j == 0):
                isprime = False
                break
        if (isprime):
            primes.append(i)

def PrimeGenerator():   # 筛选过程:从start开始筛
    primes = [2]
    Primes(primes)

    n = input()
    a = range(n)

    for i in range(n):
        a[i] = raw_input().split()

    for aa in a:
        start = int(aa[0])
        end = int(aa[-1])
        length = end - start + 1
        l = [True] * length
        for i in primes:
            if i > sqrt(end):
                break
            if start == 1:
                k = i * 2
                while k <= end:
                    l[k-start] = False
                    k += i
                l[0] = False
            elif start == 2:
                k = i * 2
                while k <= end:
                    l[k-start] = False
                    k += i
            else:
                k = start <= i and i * 2 or i * (start / i)
                while k <= end:
                    if k >= start:
                        l[k-start] = False
                    k += i
        for i in range(length):
            if l[i]:
                print i + start
        print

PrimeGenerator()

 

这道题目Time limit < 6s,常规方法肯定会超时,所以必须使用筛法,注意要提前算好素数筛子,要不然用2 - sqrt(end)之间的自然数去筛还是会超时。

因为2 - sqrt(1,000,000,000)约有32000个自然数,但是只有3000多个素数,因此素数筛子的耗时只有自然数筛子的十分之一。

 

PS:筛子这个称呼是我顺口说出来的,懂筛法的同学应该好理解,若有不正确之处,欢迎指教。

posted on 2013-10-28 10:16  SZlibraco  阅读(288)  评论(0编辑  收藏  举报