Another quick challenge via Fermat's Library:
Via Wikipedia:
A permutable prime, also known as anagrammatic prime, is a prime number which, in a given base, can have its digits' positions switched through any permutation and still be a prime number.
Here is the list of permutable primers under 1,000:
2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, 97, 113, 131, 199, 311, 337, 373, 733, 919, 991
In the language of your choice, write a script to find permutable primes.
Happy coding! 🤓
Top comments (6)
Nice one!
This solution has a bug but happens to produce the correct output. This doesn't test all permutations of digits. An n digit integer has n! permutations, but this only tests n of them. For example, 241 has six permutations (241, 214, 421, 412, 124, 142) but this only tests three (241 , 412, 124) of them.
It happens to work because all the three digit permutable prime happen to belong to a family that contain repeated digits, so you never get a false positive. It will fail for larger numbers, it will report 1193 as a permutable number, but it's not (1139 is not a prime number). It's a circular number, solved by Jonathan's Go code below.
Amazingly the next number in the permutable prime sequence after 991 is 1111111111111111111.
You can of course easily fix the bug with itertools.permutations). Just replace perms(p) with this:
Pretty long compared to the Python version by Florian Rohrer.
It uses
Sieve of Eratosthenes
to generate prime numbers up to 1000.Then just compares if all permutations of each prime number are in the prime set.
The main method that does the job is
GetPermutablePrimes
.So this doesn't sort... But on the other hand it uses recursive generators, so that has to be a good thing, right?
Ruby✨💎✨
A friend of mine got this as an interview question, and asked me about it. I wrote this solution in Go:
jmcphers.github.io/programming/201...