Truncatable primes: Difference between revisions
Content added Content deleted
(→{{header|Python}}: Add comments) |
(→{{header|Python}}: first draft) |
||
Line 5: | Line 5: | ||
C.f: [[Sieve of Eratosthenes]]; [http://mathworld.wolfram.com/TruncatablePrime.html Truncatable Prime] from Mathworld. |
C.f: [[Sieve of Eratosthenes]]; [http://mathworld.wolfram.com/TruncatablePrime.html Truncatable Prime] from Mathworld. |
||
== {{header|J}} == |
|||
<lang j> isprime=: 1&p: |
|||
filterprimes=: #~ isprime |
|||
primesbelow=: filterprimes@i.@- |
|||
isprimeRT=: ([: *./@:isprime 0&".\)@":"0 |
|||
isprimeLT=: ([: *./@:isprime 0&".\.)@":"0 |
|||
({~ i.&1@:isprimeLT) primesbelow 1e6 |
|||
999907 |
|||
({~ i.&1@:isprimeRT) primesbelow 1e6 |
|||
739399</lang> |
|||
== {{header|Python}} == |
== {{header|Python}} == |
Revision as of 01:12, 9 September 2010
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
A truncatable prime is prime number that when you successively remove digits from one end of the prime, you are left with a new prime number; for example, the number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime.
The task is to find the largest left-truncatable and right-truncatable primes less than one million.
C.f: Sieve of Eratosthenes; Truncatable Prime from Mathworld.
J
<lang j> isprime=: 1&p:
filterprimes=: #~ isprime primesbelow=: filterprimes@i.@- isprimeRT=: ([: *./@:isprime 0&".\)@":"0 isprimeLT=: ([: *./@:isprime 0&".\.)@":"0
({~ i.&1@:isprimeLT) primesbelow 1e6
999907
({~ i.&1@:isprimeRT) primesbelow 1e6
739399</lang>
Python
<lang python>maxprime = 1000000
def primes(n):
multiples = set() prime = [] for i in range(2, n+1): if i not in multiples: prime.append(i) multiples.update(set(range(i*i, n+1, i))) return prime
def truncatableprime(n):
'Return a longest left and right truncatable primes below n' primelist = [str(x) for x in primes(n)[::-1]] primeset = set(primelist) for n in primelist: # n = 'abc'; [n[i:] for i in range(len(n))] -> ['abc', 'bc', 'c'] alltruncs = set(n[i:] for i in range(len(n))) if alltruncs.issubset(primeset): truncateleft = int(n) break for n in primelist: # n = 'abc'; [n[:i+1] for i in range(len(n))] -> ['a', 'ab', 'abc'] alltruncs = set([n[:i+1] for i in range(len(n))]) if alltruncs.issubset(primeset): truncateright = int(n) break return truncateleft, truncateright
print(truncatableprime(maxprime))</lang>
Sample Output
(998443, 739399)