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:
if j == 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:
def prime(number):
return number > 1 and all(number % i != 0 for i in range(2, number))
def rotations(num):
rotated = []
m = str(num)
for _ in m:
rotated.append(int(m))
m = m[1:] + m[0]
return rotated
def prime_count(limit):
counter = 0
for number in range(1, limit + 1):
if all(prime(rotation) for rotation in rotations(number)):
counter += 1
return 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 in range(1,limit+1):
a=rotations(i)
for j in a:
if j == prime(j): # Prime will return True or False, comapring with J will cause it False ,except when J = 1
counter+=1
Changing it to prime(j)
Solution 4:
for i in range(2,number//2):
if(number%i==0):
return False
return True
def rotations(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
def get_circular_prime_count(limit):
count=0
for i in range(1,limit+1):
a=rotations(i)
for j in a:
if(check_prime(j)):
count+=1
return count
print(get_circular_prime_count(1000) ```
Post a Comment for "Python - Finding Circular Prime Number"