Friday, September 22, 2017

Circular Primes

Circular Primes
In [1]:
_sieve_limit = 1000000
isPrime = [True] * _sieve_limit

def init_sieve():
    for x in range(4, _sieve_limit, 2):
        isPrime[x]=False
    
    for x in range(3, int(_sieve_limit ** 0.5) + 1,2):
        if isPrime[x]: 
            for i in range(x*x, _sieve_limit, x):
                isPrime[i] = False

init_sieve()
In [2]:
def rotate(s,k):
    return(int(s[k:]+s[:k]))
In [3]:
# 1-digit Circular Primes
L1=[2, 3, 5, 7] 
print(L1)
[2, 3, 5, 7]
In [4]:
# 2-digit Circular Primes 
L2=[11, 13, 17, 31, 37, 71, 73, 79, 97]
print(L2)
[11, 13, 17, 31, 37, 71, 73, 79, 97]
In [5]:
# 3-digit Circular Primes
L3=[]
for n in range(100,999):
    if isPrime[n]:
        if n in L3:
            continue
        else:
            work=str(n)
            n2=rotate(work,1)
            n3=rotate(work,2)
            if isPrime[n2] and isPrime[n3]:
                L3.extend([n,n2,n3])
print(L3)
[113, 131, 311, 197, 971, 719, 199, 991, 919, 337, 373, 733]
In [6]:
# 4-digit Circular Primes
L4=[]
for n in range(1000,9999):
    if isPrime[n]:
        if n in L4:
            continue
        else:
            work=str(n)
            n2=rotate(work,1)
            n3=rotate(work,2)
            n4=rotate(work,3)
            if isPrime[n2] and isPrime[n3] and isPrime[n4]:
                L4.extend([n,n2,n3,n4])
print(L4)
[1193, 1931, 9311, 3119, 3779, 7793, 7937, 9377]
In [7]:
# 5-digit Circular Primes
L5=[]
for n in range(10000,99999):
    if isPrime[n]:
        if n in L5:
            continue
        else:
            work=str(n)
            n2=rotate(work,1)
            n3=rotate(work,2)
            n4=rotate(work,3)
            n5=rotate(work,4)
            if isPrime[n2] and isPrime[n3] and isPrime[n4] and isPrime[n5]:
                L5.extend([n,n2,n3,n4,n5])
print(L5)
[11939, 19391, 93911, 39119, 91193, 19937, 99371, 93719, 37199, 71993]