https://projecteuler.net/problem=35
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
方法很简单,快速算出100万以下的所有素数,然后在素数里面,进行查找,满足要求了,就把一整串(所有循环的数)都加到结果集里面,凡是已经加进去的不再参与查找,直到查找完成.
def CircularPrimes():
#算100万以下的素数
PrimeList = MillionPrimes()
#保存结果集
result = set()
for i in range(2,1000001):
#凡是是素数的,也不再结果集的,都拿来进行判断
if PrimeList[i] and i not in result:
#判断数字的循环序列,如果都是素数,就加到结果集中
Cirsular(i,PrimeList,result)
return len(result)
def MillionPrimes():
primeList=[True]*1000001
for i in range(2,1000001):
if primeList[i] == True:
mul = 2
while i * mul < 1000001:
primeList[i * mul] = False
mul+=1
return primeList
def Cirsular(num,List,Set):
CirsularList = [num]
#数字的长度
lenI=len(str(num))
#如果就一位的话,直接放进去,不用循环了
if lenI == 1:
Set.add(num)
return 0
tmp = num
for i in range(1,lenI):
#循环计算下一个数字,如果不是素数,则直接退出
tmp = nextCircular(tmp,lenI-1)
if not List[tmp]:
return 0
CirsularList.append(tmp)
#计算完成,都是素数,加到集合里面
for i in CirsularList:
Set.add(i)
def nextCircular(num,lenNum):
first,second = divmod(num,10)
return second * (10** lenNum) + first
print(CircularPrimes())