python - 找到圆形素数 [英] python - finding circular prime number
问题描述
我正在尝试从给定的限制中找到圆形素数的数量.prime(x) 将返回一个数字是否为素数.rotations() 将返回一个旋转数字列表.最后, prime_count() 将根据给定的限制输出循环素数的总数.prime() 和 rotations() 都给了我正确的输出;然而, prime_count() 并没有像它应该的那样递增.关于我做错了什么的任何想法?
I am trying trying to find the number of circular primes from a given limit. The prime(x) will return whether a number is a prime or not. The rotations() will return a list of rotated numbers. Lastly, prime_count() will output the total amount of circular primes based on the given limit. Both prime() and rotations() gave me the correct output; however, prime_count() is not incrementing like it should. Any ideas on what i did wrong?
def prime(number): #return true or false
return all(number% i for i in range(2,number))
def rotations(num): #rotating number and return list
list = []
m = str(num)
counter = 0
while counter < len(str(num)):
m=m[1:] + m[0]
list.append(int(m))
counter+=1
list1=sorted(list,key=int)
return list1
def prime_count(limit): #return numbers of circular primes from given limit
counter = 0
for i in range(1,limit+1):
a=rotations(i)
for j in a:
if j == prime(j):
counter+=1
return counter
print(prime_count(100))
推荐答案
您的代码存在一些问题:
There are a few problems with your code:
你的
prime
函数有一个错误:
In [8]: prime(1)
Out[8]: True
由于 range(2, n)
为空且 any([]) == True<,它错误地为任何小于 2 的数字返回
True
/code>.
It erroneously returns True
for any number less than 2 due to range(2, n)
being empty and any([]) == True
.
prime_count
应该计算低于 limit
的循环素数的总数.prime(j)
返回一个布尔值,但您检查 j == prime(j)
,只有当 j
为零或一,这绝对不是你想要的.尝试创建一个 is_circular_prime
函数,它接受一个整数 n
并返回素数是否是循环的.然后,prime_count
变得容易编写.
prime_count
should be counting the total number of circular primes below limit
. prime(j)
returns a boolean, but you check j == prime(j)
, which can only be true if j
is zero or one, which definitely isn't what you want. Try creating an is_circular_prime
function that takes in an integer n
and returns whether or not the prime is circular. Then, prime_count
becomes easy to write.
这篇关于python - 找到圆形素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!