Back to Project Euler

Previous Problem Next Problem

Problem 35: 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?

Solution

All primes with more than one digit have a final digit of 1, 3, 7, or 9. It follows that every digit in a circular prime must be 1, 3, 7, or 9, so we can save ourselves some time by only considering numbers with those digits. I do this via the product function in Python's itertools module.

Python Code

from itertools import product
from sympy import isprime
def p35(n=6):
	res = 4  # for the single digit primes
	for r in range(2, n+1):
		for tup in product((1, 3, 7, 9), repeat=r):
			num = sum(map(lambda d: tup[d] * 10 ** d, range(r)))
			if not isprime(num):
				continue
			for rotation in range(r-1):
				num = (num // 10) + (num % 10) * 10 ** (r-1)
				if not isprime(num):
					break
			else:
				res += 1
	return res

Previous Problem Next Problem

Back to Project Euler