我试图通过计算找到的素数来将我的结果与Wolfram Alpha的结果进行比较。
看起来效果很好,没有错误。
但是当我向SPOJ提交此解决方案时,它会显示错误消息“错误答案”。
我还尝试将最终打印的end =更改为''(空白字符串),但仍然得到“错误答案”。
不确定我的筛选算法是否有问题,或输出错误。
**编辑:问题http://www.spoj.pl/problems/PRIME1/的链接
这是我的PRIME1源代码,希望有人可以指出我的错。非常感谢。
希望有人可以教我如何为这样的程序编写测试,我还在学习,不知道如何对程序进行自动化测试,但想学习。
def getPrimeInRange(minNum, maxNum):
#just a variation with skipping step of the Sieve of E's
processingRange = list(range(minNum, maxNum+1))
#prefix, due to 1 is not a prime
if minNum == 1:
processingRange[0] = 0
sqrtOfMaxNum = int(maxNum ** 0.5) + 1
primesUnderSqrt = list(range(sqrtOfMaxNum))
#prefix, due to 1 is not a prime
primesUnderSqrt[1] = 0
#my strategy is flip all numbers that is not a prime to zero, which equals to False.
#for Sieve of E's, all the primes under sqrt of max num are the only needed numbers to sieve primes out.
#so here is a smaller Sieve of E's for numbers under sqrt
for n in primesUnderSqrt:
if n: #which equals to "if n != 0"
nowIndex = n + n
while True:
try:
primesUnderSqrt[nowIndex] = 0
nowIndex += n
except IndexError:
break
#full aspect sieve
for n in primesUnderSqrt:
if n:
#for easier flip processing, I need the offset number for the flipping.
nMultipleMostCloseToMin = n * (minNum // n)
if nMultipleMostCloseToMin == minNum:
nowIndex = 0
elif sqrtOfMaxNum <= minNum:
nowIndex = nMultipleMostCloseToMin + n - minNum
elif sqrtOfMaxNum > minNum:
nowIndex = nMultipleMostCloseToMin + n - minNum + n
#happy flippin'
while True:
try:
processingRange[nowIndex] = 0
nowIndex += n
except IndexError:
break
return processingRange
def main():
todoTimes = int(input())
todoNums = list(range(todoTimes))
stringOutput = ''
for i in range(todoTimes):
todoNums[i] = input().split()
todoNums[i][0] = int(todoNums[i][0])
todoNums[i][1] = int(todoNums[i][1])
for [minNum, maxNum] in todoNums:
#countedNum = 0 #for algo debugging
for n in getPrimeInRange(minNum, maxNum):
if n:
stringOutput += str(n)
#countedNum += 1 #for algo debugging
stringOutput += '\n'
stringOutput += '\n'
#stringOutput += str(countedNum) #for algo debugging
stringOutput = stringOutput.rstrip('\n')
print(stringOutput)
ifMainSucceed = main()
答案 0 :(得分:0)
这部分逻辑
if nMultipleMostCloseToMin == minNum:
nowIndex = 0
elif sqrtOfMaxNum <= minNum:
nowIndex = nMultipleMostCloseToMin + n - minNum
elif sqrtOfMaxNum > minNum:
nowIndex = nMultipleMostCloseToMin + n - minNum + n
错了。你的elif
条件在这里没有多大意义。如果n
不是minNum
的除数,则n
不小于minNum
的最小倍数为nMultipleMostCloseToMin + n
,无论sqrtOfMaxNum
是否为minNum
是否大于n <= minNum
。你在这里想要的条件是{{1}},以避免越过素数本身。