数字197可以被称为循环素数,因为197的三个数位循环移位后的数字:197,971,719均为素数。100以内这样的数字包括13个,2,3,5,7,11,13,17,31,37,71,73,79,97。求大家帮忙算出算出1000000以内一共有多少个这样的循环素数。并把代码给我。程序运行时间要少于6秒的。谢谢了 用Python 进行编程!!Python
2 回答
已采纳
Perona
TA贡献355条经验 获得超403个赞
#!/usr/bin/python # encoding: utf-8 import time import pprint def allPrime(maxNum): aList = range(0, maxNum) def _do(aPrime): for i in xrange(aPrime, maxNum, aPrime): aList[i] = 0 return aPrime return map(_do, (i for i in xrange(2,maxNum) if aList[i]) ) t0 = time.time() LIMIT = 1000000 primelist = allPrime(LIMIT) primesets = set(primelist) def loopshift(num): numlst = list(str(num)) result = list() for i in range(len(numlst)): x = int(''.join(numlst[i:] + numlst[:i])) if x not in primesets: return None result.append(x) result = sorted(set(result)) for x in set(result): primesets.remove(x) return result found = list() for num in primelist: xn = loopshift(num) if xn and xn not in found: found.append(xn) pprint.pprint(found)
在loopshift方法中对每个数据生成所有相关循环数,再判断每一个是否都是素数
添加回答
举报
0/150
提交
取消