对于SPOJ在http://www.spoj.com/problems/PRIME1/的PRIME1问题,我得到了错误的答案。我自己在各种测试用例上测试过它,但是找不到失败的测试用例。有人能找出我代码中的问题吗?
对于不提供任何素数作为输出的测试用例,此代码不生成任何内容。首先,我预计算素数到sqrt(10亿),然后如果请求的范围具有小于sqrt(10亿)的高值,我只需从预先计算的数组中打印素数,否则我使用usePrimes=True运行sieve(),它使用预计算的素数来排除给定范围内的非素数。在
谢谢。在
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
如果将上限更改为上界=int(数学.sqrt(1000000000))+123456,则它将通过所有测试用例。在
现在,你知道为什么吗?我把它留给你练习。在
相关问题 更多 >
编程相关推荐