QUESTION: The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.代碼中的邏輯錯誤?
Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
我的代碼是唯一能夠輸出前五個這樣的數字,並顯示以下錯誤:
Traceback (most recent call last):
File "main.py", line 41, in
if check(i) and check(rev(i)):
File "main.py", line 30, in check
if sieve[n]:
IndexError: list index out of range
代碼:
sieve = [True] * 1000001 # Sieve is faster for 2M primes
def mark(sieve, x):
for i in xrange(x+x, len(sieve), x):
sieve[i] = False
sieve[0],sieve[1]=False,False
for x in xrange(2, int(len(sieve) ** 0.5) + 1):
if sieve[x]: mark(sieve, x)
def rev(n):
s=0
while n>0:
s=s*10+n%10
n/=10
return s
def check(n):
flag=1
while n>0:
if sieve[n]:
n/=10
else:
flag=0
break
return flag==1
ctr=0
i=11
s=0
while ctr!=11:
if check(i) and check(rev(i)):
print i
s+=i
ctr+=1
i+=1
print s
lww=raw_input()
你有沒有跑過篩子的盡頭? – user2357112
這似乎最有可能。你知道第11個雙向可截斷素數有多大? – jonrsharpe
如果你只是添加一些代碼來捕捉異常和'print n',我們實際上會知道這是否是問題而不是猜測... – abarnert