SPOJ prime1在python中的错误答案

时间:2013-12-31 11:47:45

标签: python algorithm sieve-of-eratosthenes

我在http://www.spoj.com/problems/PRIME1/的SPOJ的 PRIME1 问题的python中使用以下代码获取错误答案。我自己在各种测试用例上测试过它,但找不到失败的测试用例。 有人可以在我的代码中发现问题吗?

此代码不会为不提供任何素数作为输出的测试用例生成任何内容。首先,我预先计算高达sqrt(10亿)的素数,然后如果请求的范围具有小于sqrt(10亿)的高值,我只需从预先计算的数组中打印素数,否则我用usePrimes =运行sieve() 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

1 个答案:

答案 0 :(得分:0)

如果将upper_bound更改为upper_bound = int(math.sqrt(1000000000))+ 123456 ,则它将通过所有测试用例。

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