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))
@johnshumon
Copy link

johnshumon commented Jul 22, 2021

I think your solution doesn't produce correct result. For example look at the following output (copy pasted your code):

❯ python project_eu_35.py                                                                                                                                               
Enter a search limit less than 1,000,000? 30
Number of circular primes below 30  is 5
They are: [2, 3, 5, 7, 11]  With a sum of 28

As you can notice 13 and 17 are missing from the list

@betaprojects
Copy link
Author

Yes, It can be confusing with the problem definition, but if you put in a limit of 32, then 31 will show up as it is below 32. So, to be a circular prime both primes must be under the limit. HackerRank expects the same result. check out:
https://betaprojects.com/solutions/project_euler/project-euler-problem-035-solution/

@johnshumon
Copy link

😳 That's an interesting condition! Good to know. Thanks for the clarification.

@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