【发布时间】:2019-07-30 13:57:56
【问题描述】:
Problem 35, Project Euler 我的解决方案的输出停止在一个相当奇怪的点,原因超出了我目前的理解。我已经按照纸上的代码进行了操作,这对我来说似乎是正确的。
prime_list =[]
prime2 = []
prime2_up=[]
##The sieve of eratosthenes##c
def prime_sieve(n):
prime = [True for i in range(0,n+1)]
p = 2
while p*p<=n:
if prime[p] == True:
for i in range(p*p,n+1,p):
prime[i] = False
p+=1
for p in range(2,n):
if prime[p]:
prime_list.append(p)
##Check whether the given prime is circular or not##
def circular_checker():
for j in prime_list:
x = str(j)
for i in range(0,len(x)):
x = x[i:len(x)]+x[0:i]
if int(x) not in prime_list:
return False
prime2.append(int(x))
##Function To remove duplicates and sort the list##
def remove_duplicate():
for k in prime2:
if k not in prime2_up:
prime2_up.append(k)
prime2_up.sort()
prime_sieve(1000)
circular_checker()
remove_duplicate()
print(prime2_up)
我希望输出是一个最大为 1000 的循环素数列表,但该列表突然停在 19 处。
输出: [2、3、5、7、11、31、71]
请说明我的解决方案中的缺陷,并说明相关原因。
编辑 1
感谢@khelwood 和@dollarAkshay 的有用回复。但现在我面临一个过度计数的新问题。 更新后的代码表示的循环素数是121,这确实是错误的。
##updated part, also the exclusion of numbers with digits 2,4,6,8,0 and 5 to reduce runtime##
def circular_checker():
for j in prime_list:
x = str(j)
circular = True
for i in range(0,len(x)):
x = x[i:len(x)]+x[0:i]
if not prime[int(x)] or "2" in x or "4" in x or "6" in x or "8" in x or "0" in x or "5" in x:
circular = False
break
if circular:
prime2.append(int(x))
prime_sieve(1000000)
circular_checker()
prime2_up.append(2)
prime2_up.append(5)
remove_duplicate()
print(len(prime2_up))
【问题讨论】:
-
下一个圆形素数应该是什么?
-
应该有 13, 17 但你问下一个是 79
-
您可以通过制作一组来删除重复项:
prime2_up = list(sorted(set(prime2))),或者更好的是,从一开始就使用一组 -
@khelwood
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. -
您的
circular_checker在循环中间有一个 return false 。这将退出您的整个循环,因此此后将不再检查素数。
标签: python python-3.x math output