Tim Varley Logo
Tim Varley Systems Engineer
Problem #35 hard

Circular Primes

The number, 197197, is called a circular prime because all rotations of the digits: 197197, 971971, and 719719, are themselves prime.

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

How many circular primes are there below one million?

Implementations

cpp
// Answer: 55
// Authored by: Tim Varley 💘
// Assisted-by: Grok Code Fast via Crush 💘 <crush@charm.land>
#include <iostream>
#include <vector>
#include <string>
int circular_primes() {
const int MAX = 1000000;
std::vector<bool> is_prime(MAX+1, true);
is_prime[0] = is_prime[1] = false;
for(long long i=2; i*i<=MAX; i++) {
if(is_prime[i]) {
for(long long j=i*i; j<=MAX; j+=i) {
is_prime[j] = false;
}
}
}
int count = 0;
for(int n=2; n<MAX; n++) {
if(!is_prime[n]) continue;
std::string s = std::to_string(n);
bool all_prime = true;
for(size_t rot=1; rot<s.size(); rot++) {
std::string r = s.substr(rot) + s.substr(0,rot);
int rn = std::stoi(r);
if(!is_prime[rn]) { all_prime=false; break; }
}
if(all_prime) count++;
}
return count;
}
#if ! defined UNITTEST_MODE
int main(int argc, char const *argv[]) {
std::cout << circular_primes() << std::endl;
}
#endif // UNITTEST_MODE

Solution Notes

Mathematical Background

A circular prime is a prime number where all rotations of its digits are also prime. For example, 197 → 971 → 719, all prime.

This requires checking that every cyclic permutation of the digits forms a prime number, excluding leading zeros in rotations.

Algorithm Analysis

The implementations combine the Sieve of Eratosthenes with rotation checking:

  • Generate all primes below 1,000,000 using the sieve
  • For each prime, generate all digit rotations
  • Check if every rotation is also prime
  • Count primes that satisfy this property

Single-digit primes (2, 3, 5, 7) are circular by definition.

Performance Analysis

  • Time Complexity: O(n log log n) for sieve + O(π(n) × d × √n) for rotation checks, where π(n) is prime-counting function (~78,000 for n=1M) and d is digits (~6). Total ~10^7 operations, executes in seconds.
  • Space Complexity: O(n) for the sieve array (1M booleans).
  • Execution Time: Fast (1-2 seconds), suitable for batch processing.
  • Scalability: Linear in n for sieve, but rotation checks grow with number of primes.

Key Insights

  • There are 55 circular primes below 1,000,000
  • All single-digit primes are circular
  • Numbers containing even digits or 5 (except as first digit) cannot be circular primes
  • The sieve enables O(1) primality lookups for rotations

Educational Value

This problem teaches:

  • The Sieve of Eratosthenes for prime generation
  • String rotation algorithms and cyclic permutations
  • Combining multiple algorithmic techniques
  • The properties of primes and digit patterns
  • Optimization through precomputation and lookup tables