Circular primes

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.

There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.

How many circular primes are there below one million?


Idea

The key to this problem is to reduce search space.

  • a number containing any even digit could not be circular prime
  • a number containing 5 could not be circular prime
  • a number which sum of all digits can be divided by 3 could not be circular prime

Also, if a number is not circular prime, then all of its circular numbers could not be circular prime. This could avoid twice-calculation.


In [1]:
import math
In [2]:
def could_be_circular_prime(n):
    digits = list(map(int, str(n)))
    digit_number = len(digits)
    if any(map(lambda d: d % 2 == 0, digits)):
        return False
    elif 5 in digits:
        return False
    elif sum(digits) % 3 == 0:
        return False
    return True
In [3]:
def circular(n):
    circulars = []
    digit_number = len(str(n))
    power = pow(10, digit_number-1)
    for _ in range(digit_number):
        circulars.append(n)
        n = (n % 10) * power + n // 10
    return set(circulars)
In [4]:
def is_prime(n):
    if (n % 2 == 0 and n > 2) or n < 2: 
        return False
    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
In [5]:
def solve(bound):
    circular_primes = set([2, 3, 5])
    candidates = set(filter(could_be_circular_prime, range(2, int(bound))))
    while candidates:
        c = candidates.pop()
        circulars = circular(c)
        if all(map(is_prime, circulars)):
            circular_primes |= circulars
        candidates -= circulars

    return len(circular_primes), circular_primes
In [6]:
solve(100)
Out[6]:
(13, {2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, 97})
In [7]:
solve(1e6)
Out[7]:
(55,
 {2,
  3,
  5,
  7,
  11,
  13,
  17,
  31,
  37,
  71,
  73,
  79,
  97,
  113,
  131,
  197,
  199,
  311,
  337,
  373,
  719,
  733,
  919,
  971,
  991,
  1193,
  1931,
  3119,
  3779,
  7793,
  7937,
  9311,
  9377,
  11939,
  19391,
  19937,
  37199,
  39119,
  71993,
  91193,
  93719,
  93911,
  99371,
  193939,
  199933,
  319993,
  331999,
  391939,
  393919,
  919393,
  933199,
  939193,
  939391,
  993319,
  999331})