Skip to content

Instantly share code, notes, and snippets.

@betaprojects
Last active July 23, 2021 07:30
Show Gist options
  • Save betaprojects/5539338b1881625a4f30025cd87c2950 to your computer and use it in GitHub Desktop.
Save betaprojects/5539338b1881625a4f30025cd87c2950 to your computer and use it in GitHub Desktop.
Project Euler & HackerRank problem 35 solution: Find the number of circular primes below one million - solved using Python
prime_sieve()
<def prime_sieve(n):
    sieve = [True] * (n//2)
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1)
    return [2] + [2*i+1 for i in range(1,n//2) if sieve[i]]
def rotate(s):
    return [s[n:] + s[:n] for n in range(1, len(s))]

s = set('024568')
L = int(input("Enter a search limit less than 1,000,000? "))
primes = set(['2','5']+[p for p in map(str, prime_sieve(L)) if not set(p).intersection(s)])
circular_primes = [int(p) for p in primes if all(pr in primes for pr in rotate(p))]

print ("Number of circular primes below", L, " is",len(circular_primes))
print ("They are:", sorted(circular_primes), " With a sum of",sum(circular_primes))
@betaprojects
Copy link
Author

betaprojects commented Jul 22, 2021

Thanks for asking the question. It's definitely open to interpretation. Although this solution was accepted by HackerRank I'm beginning to wonder why your view is not a better answer. Maybe just generate all circular primes below 1 million to a list and just reference that list for circular primes queries for 10<=N<1,000,000. Thanks for making me think about this again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment