SPOJ prime1在python中的错误答案

SPOJ prime1在python中的错误答案,python,algorithm,sieve-of-eratosthenes,Python,Algorithm,Sieve Of Eratosthenes,我用python中的以下代码来回答SPOJ的PRIME1问题,结果是错误的。我自己已经在各种测试用例上测试过它,但是找不到失败的测试用例。有人能找出我代码中的问题吗 对于不提供任何素数作为输出的测试用例,此代码不生成任何结果。首先,我预先计算高达sqrt1十亿的素数,然后如果请求的范围具有小于sqrt1十亿的高值,我只需从预先计算的数组中打印素数,否则我使用usePrimes=True运行筛选,它使用预先计算的素数排除给定范围内的非素数 谢谢 import math from bisect im

我用python中的以下代码来回答SPOJ的PRIME1问题,结果是错误的。我自己已经在各种测试用例上测试过它,但是找不到失败的测试用例。有人能找出我代码中的问题吗

对于不提供任何素数作为输出的测试用例,此代码不生成任何结果。首先,我预先计算高达sqrt1十亿的素数,然后如果请求的范围具有小于sqrt1十亿的高值,我只需从预先计算的数组中打印素数,否则我使用usePrimes=True运行筛选,它使用预先计算的素数排除给定范围内的非素数

谢谢

import math
from bisect import bisect_left
from bisect import bisect_right

primes = []
upper_bound = int(math.sqrt(1000000000)) + 1
usePrimes = False
printNL = False
T = 0

def sieve(lo, hi):
    global usePrimes, primes, printNL
    atleast_one = False
    arr = range(lo,hi+1)
    if usePrimes:
        for p in primes:
            if p*p > hi:
                break
            less = int(lo/p) * p
            if less < lo:
                less += p
            while less <= hi:
                arr[less - lo] = 0
                less += p
        for num in arr:
            if num  != 0:
                atleast_one = True
                if printNL:
                    print ''
                    printNL = False
                print num
    else:
        atleast_one = True
        for k in xrange(2,hi):
            if k*k > hi:
                break
            if arr[k] == 0:
                continue
            less = k + k
            while less <= hi:
                arr[less] = 0
                less += k
        for num in arr:
            if num > 1:
                primes.append(num)
    return atleast_one


def printPrimesInRange(lo,hi):
    global primes, printNL
    atleast_one = False
    if hi < upper_bound:
        for p in primes[bisect_left(primes,lo):bisect_right(primes,hi)]:
            atleast_one = True
            if printNL:
                print ''
                printNL = False
            print p
    else:
        atleast_one = sieve(lo,hi)
    return atleast_one

sieve(0, upper_bound)
usePrimes = True

T = input()
while T > 0:
    lo, hi = [eval(y) for y in raw_input().split(' ')]
    atleastOne = printPrimesInRange(lo,hi)
    if atleastOne:
        printNL = True
    T -= 1

如果将上限更改为上限=intmath.sqrt100000000+123456,那么它将通过所有测试用例


现在,你能理解为什么会这样吗?我将把它作为练习留给你。

我不懂Python。打印p是否自动附加CR/LF?指令上说每行一个素数,这就是它实际打印的内容吗?是的,打印会自动附加一个CR/LF,我已经检查了输出,它每行一个素数。