Python - Finding Circular Prime Number
Solution 1:
There are a few problems with your code:
Your
prime
function has a bug:In [8]: prime(1) Out[8]: True
It erroneously returns
True
for any number less than 2 due torange(2, n)
being empty andany([]) == True
.prime_count
should be counting the total number of circular primes belowlimit
.prime(j)
returns a boolean, but you checkj == prime(j)
, which can only be true ifj
is zero or one, which definitely isn't what you want. Try creating anis_circular_prime
function that takes in an integern
and returns whether or not the prime is circular. Then,prime_count
becomes easy to write.
Solution 2:
This is the heart of the problem:
a=rotations(i)
for j in a:
ifj== prime(j):
counter+=1
You're counting the wrong thing (e.g. 13 counts twice independent of 31 counting twice) and you're comparing the wrong thing (numbers against booleans.) The problem is simpler than you're making it. Rearranging your code:
defprime(number):
return number > 1andall(number % i != 0for i inrange(2, number))
defrotations(num):
rotated = []
m = str(num)
for _ in m:
rotated.append(int(m))
m = m[1:] + m[0]
return rotated
defprime_count(limit):
counter = 0for number inrange(1, limit + 1):
ifall(prime(rotation) for rotation in rotations(number)):
counter += 1return counter
print(prime_count(100))
Note that you don't need to sort the rotations for this purpose. Also list
, or any other Python built-in function, is a bad name for a variable.
Solution 3:
Problem may be here:
for i inrange(1,limit+1):
a=rotations(i)
for j in a:
if j == prime(j): # Prime will returnTrueorFalse, comapring with J will cause it False ,exceptwhen J =1
counter+=1
Changing it to prime(j)
Solution 4:
for i inrange(2,number//2):
if(number%i==0):
returnFalsereturnTruedefrotations(num):
count=0
rotation_lst=[]
num=str(num)
while(count<len(num)):
num=num[1:]+num[0]
count+=1
rotation_lst.append(int(num))
rotation_lst1=sorted(rotation_lst,key=int)
return rotation_lst1
defget_circular_prime_count(limit):
count=0for i inrange(1,limit+1):
a=rotations(i)
for j in a:
if(check_prime(j)):
count+=1return count
print(get_circular_prime_count(1000) ```
Post a Comment for "Python - Finding Circular Prime Number"