Emirp primes: Difference between revisions

m
 
(43 intermediate revisions by 30 users not shown)
Line 1:
{{task|Prime numbersNumbers}}
 
An   ''emirp''   ('''prime''' spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime.
Line 25:
*   [https://oeis.org/A006567 The On‑Line Encyclopedia of Integer Sequences, emirps (A6567)].
<br><br>
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">F reversed(Int =n)
V result = 0
L
result = 10 * result + n % 10
n I/= 10
I n == 0
R result
 
V limit = 1'000'000
V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
I is_prime[n]
L(i) (n * n .< limit + 1).step(n)
is_prime[i] = 0B
 
F is_emirp(n)
I !:is_prime[n]
R 0B
V r = reversed(n)
R r != n & :is_prime[r]
 
print(‘First 20 emirps:’, end' ‘’)
V count = 0
L(n) 0 .< limit
I is_emirp(n)
print(‘ ’n, end' ‘’)
I ++count == 20
L.break
print()
 
print(‘Emirps between 7700 and 8000:’, end' ‘’)
L(n) 7700..8000
I is_emirp(n)
print(‘ ’n, end' ‘’)
print()
 
count = 0
L(n) 0 .< limit
I is_emirp(n)
I ++count == 10000
print(‘The 10000th emirp: ’n)
L.break</syntaxhighlight>
 
{{out}}
<pre>
First 20 emirps: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Emirps between 7700 and 8000: 7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
The 10000th emirp: 948349
</pre>
 
=={{header|Ada}}==
Line 30 ⟶ 83:
he solution uses the package Miller_Rabin from the [[Miller-Rabin primality test]].
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Miller_Rabin;
 
procedure Emirp_Gen is
Line 98 ⟶ 151:
end loop;
Ada.Text_IO.Put_Line(Num'Image(Current));
end Emirp_Gen;</langsyntaxhighlight>
 
{{out}}
Line 109 ⟶ 162:
Uses Algol 68G specific argc and argv procedures to access to command line.
Allows the user to specify the from and to range values or ordinals on the command line. The sieve size can also be specified. As suggested by the Fortran sample, from = to is treated as a special case for labeling the output.
{{libheader|ALGOL 68-primes}}
<lang algol68># sieve of Eratosthenes: sets s[i] to TRUE if i is prime, FALSE otherwise #
<syntaxhighlight lang="algol68"># parse the command line - ignore errors #
PROC sieve = ( REF[]BOOL s )VOID:
BEGIN
# start with everything flagged as prime #
FOR i TO UPB s DO s[ i ] := TRUE OD;
# sieve out the non-primes #
s[ 1 ] := FALSE;
FOR i FROM 2 TO ENTIER sqrt( UPB s ) DO
IF s[ i ] THEN FOR p FROM i * i BY i TO UPB s DO s[ p ] := FALSE OD FI
OD
END # sieve # ;
 
# parse the command line - ignore errors #
INT emirp from := 1; # lowest emirp required #
INT emirp to := 10; # highest emirp required #
Line 153 ⟶ 195:
 
# construct a sieve of primes up to the maximum number required for the task #
PR read "primes.incl.a68" PR
[ 1 : max number ]BOOL is prime;
sieve([]BOOL is prime )= PRIMESIEVE max number;
 
# return TRUE if p is an emirp, FALSE otherwise #
Line 200 ⟶ 242:
OD
FI;
print( ( newline ) )</langsyntaxhighlight>
{{out}}
a68g emirpPrimes.a68 - FROM 1 TO 20
Line 214 ⟶ 256:
emirp 10000: 948349
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">emirps: function [upto][
result: new []
loop range .step: 2 11 upto 'x [
if prime? x [
reversed: to :integer reverse to :string x
if x <> reversed [
if prime? reversed ->
'result ++ x
]
]
]
return result
]
 
lst: emirps 1000000
 
print "The first 20 emirps:"
print first.n: 20 lst
 
print ""
print "Emirps between 7700 and 8000:"
print select lst 'x -> and? x > 7700 x < 8000
 
print ""
print "The 10000th emirp:"
print lst\9999</syntaxhighlight>
 
{{out}}
 
<pre>The first 20 emirps:
13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
 
Emirps between 7700 and 8000:
7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
 
The 10000th emirp:
948349</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">SetBatchLines, -1
p := 1
Loop, 20 {
Line 276 ⟶ 358:
r := A_LoopField r
return r
}</langsyntaxhighlight>
{{Output}}
<pre>First twenty emirps: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Line 286 ⟶ 368:
 
cat emirp.awk
<syntaxhighlight lang="awk">
<lang AWK>
function is_prime(n, p)
{
Line 332 ⟶ 414:
printf("\n")
}
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 340 ⟶ 422:
948349
</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> REM Taking advantage of inbuilt assembler to implement ultra fast Prime tester!
DIM P% 127:[OPT 0
.F% pop eax:mov eax,0:.T% ret:.M% mov eax,ecx:xor edx,edx:div ebx:cmp edx,0:jz F%:ret
.E% mov ebx,2:call M%:mov ebx,3:call M%:mov ebx,5:.W% mov edx,ebx:imul edx,ebx
cmp edx,ecx:jg T%:call M%:add ebx,2:call M%:add ebx,4:jmp W%:]
DEF FNIsPrime(C%)=USRE%
 
N%=0
P%=11
PRINT "First 20 emirps are:";
WHILE N%<10000
P%+=2
IF FNIsPrime(P%) THEN
R%=VALFNRev(STR$P%)
IF P%<>R% IF FNIsPrime(R%) THEN
IF N%<20 OR (P%>7699 AND P%<8001) PRINT " ";P%;
N%+=1
IF N%=20 PRINT '"Emirps between 7700 and 8000 are:";
ENDIF
ENDIF
ENDWHILE
PRINT '"The 10,000th emirp is: ";P%
END
 
DEF FNRev(n$)
Q%=!^n$
L%=LENn$-1
FOR I%=0 TO L%/2 SWAP Q%?I%, Q%?(L%-I%) NEXT
=n$</syntaxhighlight>
{{out}}
<pre>First 20 emirps are: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Emirps between 7700 and 8000 are: 7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
The 10,000th emirp is: 948349</pre>
 
=={{header|C}}==
Note the unusual commandline argument parsing to sastisfy the "invoke three times" magic requirement.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
typedef unsigned uint;
Line 394 ⟶ 512:
putchar('\n');
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 405 ⟶ 523:
</pre>
 
=={{header|C++ sharp|C#}}==
<lang Cpp>#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
#include <cmath>
 
bool isPrime ( int number ) {
if ( number <= 1 )
return false ;
if ( number == 2 )
return true ;
for ( int i = 2 ; i <= std::sqrt( number ) ; i++ ) {
if ( number % i == 0 )
return false ;
}
return true ;
}
 
int reverseNumber ( int n ) {
std::ostringstream oss ;
oss << n ;
std::string numberstring ( oss.str( ) ) ;
std::reverse ( numberstring.begin( ) , numberstring.end( ) ) ;
return std::stoi ( numberstring ) ;
}
 
bool isEmirp ( int n ) {
return isPrime ( n ) && isPrime ( reverseNumber ( n ) )
&& n != reverseNumber ( n ) ;
}
 
int main( ) {
std::vector<int> emirps ;
int i = 1 ;
while ( emirps.size( ) < 20 ) {
if ( isEmirp( i ) ) {
emirps.push_back( i ) ;
}
i++ ;
}
std::cout << "The first 20 emirps:\n" ;
for ( int i : emirps )
std::cout << i << " " ;
std::cout << '\n' ;
int newstart = 7700 ;
while ( newstart < 8001 ) {
if ( isEmirp ( newstart ) )
std::cout << newstart << '\n' ;
newstart++ ;
}
while ( emirps.size( ) < 10000 ) {
if ( isEmirp ( i ) ) {
emirps.push_back( i ) ;
}
i++ ;
}
std::cout << "the 10000th emirp is " << emirps[9999] << " !\n" ;
 
return 0 ;
}</lang>
{{out}}
<pre>13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
7717
7757
7817
7841
7867
7879
7901
7927
7949
7951
7963
the 10000th emirp is 948349 !
</pre>
 
=={{header|C sharp}}==
{{works with|C sharp|7}}
<langsyntaxhighlight lang="csharp">using static System.Console;
using System;
using System.Linq;
Line 554 ⟶ 594:
return reverse;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 565 ⟶ 605:
10000th:
948349
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
#include <cmath>
 
bool isPrime ( int number ) {
if ( number <= 1 )
return false ;
if ( number == 2 )
return true ;
for ( int i = 2 ; i <= std::sqrt( number ) ; i++ ) {
if ( number % i == 0 )
return false ;
}
return true ;
}
 
int reverseNumber ( int n ) {
std::ostringstream oss ;
oss << n ;
std::string numberstring ( oss.str( ) ) ;
std::reverse ( numberstring.begin( ) , numberstring.end( ) ) ;
return std::stoi ( numberstring ) ;
}
 
bool isEmirp ( int n ) {
return isPrime ( n ) && isPrime ( reverseNumber ( n ) )
&& n != reverseNumber ( n ) ;
}
 
int main( ) {
std::vector<int> emirps ;
int i = 1 ;
while ( emirps.size( ) < 20 ) {
if ( isEmirp( i ) ) {
emirps.push_back( i ) ;
}
i++ ;
}
std::cout << "The first 20 emirps:\n" ;
for ( int i : emirps )
std::cout << i << " " ;
std::cout << '\n' ;
int newstart = 7700 ;
while ( newstart < 8001 ) {
if ( isEmirp ( newstart ) )
std::cout << newstart << '\n' ;
newstart++ ;
}
while ( emirps.size( ) < 10000 ) {
if ( isEmirp ( i ) ) {
emirps.push_back( i ) ;
}
i++ ;
}
std::cout << "the 10000th emirp is " << emirps[9999] << " !\n" ;
 
return 0 ;
}</syntaxhighlight>
{{out}}
<pre>13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
7717
7757
7817
7841
7867
7879
7901
7927
7949
7951
7963
the 10000th emirp is 948349 !
</pre>
 
Line 570 ⟶ 688:
===Using biginteger's isProbablePrime()===
The isProbablePrime() method performs a Miller-Rabin primality test to within a given certainty.
<langsyntaxhighlight lang="clojure">(defn emirp? [v]
(let [a (biginteger v)
b (biginteger (clojure.string/reverse (str v)))]
Line 582 ⟶ 700:
(println "10,000: " (nth (filter emirp? (iterate inc 0)) 9999))
 
</syntaxhighlight>
</lang>
{{out}}
<pre>first20: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Line 588 ⟶ 706:
10,000: 948349
</pre>
 
=={{header|Common Lisp}}==
 
It uses a primitive prime function found in http://www.rosettacode.org/wiki/Primality_by_trial_division, not optimized at all.
<syntaxhighlight lang="lisp">(defun primep (n)
"Is N prime?"
(and (> n 1)
(or (= n 2) (oddp n))
(loop for i from 3 to (isqrt n) by 2
never (zerop (rem n i)))))
 
(defun reverse-digits (n)
(labels ((next (n v)
(if (zerop n) v
(multiple-value-bind (q r)
(truncate n 10)
(next q (+ (* v 10) r))))))
(next n 0)))
 
(defun emirp (&key (count nil) (start 10) (end nil) (print-all nil))
(do* ((n start (1+ n))
(c count) )
((or (and count (<= c 0)) (and end (>= n end))))
(when (and (primep n) (not (= n (reverse-digits n))) (primep (reverse-digits n)))
(when print-all (format t "~a " n))
(when count (decf c)) )))
 
 
(progn
(format t "First 20 emirps: ") (emirp :count 20 :print-all t)
(format t "~%Emirps between 7700 and 8000: ") (emirp :start 7700 :end 8000 :print-all t)
(format t "~%The 10,000'th emirp: ") (emirp :count 10000 :print-all nil) )
</syntaxhighlight>
 
{{out}}
<pre>First 20 emirps: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Emirps between 7700 and 8000: 7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
The 10,000'th emirp: 948349</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">bool isEmirp(uint n) pure nothrow @nogc {
bool isPrime(in uint n) pure nothrow @nogc {
if (n == 2 || n == 3)
Line 623 ⟶ 779:
iota(7_700, 8_001).filter!isEmirp);
writeln("10000th: ", uints.filter!isEmirp.drop(9_999).front);
}</langsyntaxhighlight>
{{out}}
<pre>First 20:
Line 633 ⟶ 789:
 
===Sieve-Based Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.bitmanip;
 
/// Not extendible Sieve of Eratosthenes.
Line 675 ⟶ 831:
iota(7_700, 8_001).filter!isEmirp);
writeln("10000th: ", uints.filter!isEmirp.drop(9_999).front);
}</langsyntaxhighlight>
The output is the same. With ldc2 compiler the run-time is about 0.06 seconds.
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Emirp_primes#Pascal Pascal].
 
=={{header|EasyLang}}==
<syntaxhighlight>
fastfunc isprim num .
i = 2
while i <= sqrt num
if num mod i = 0
return 0
.
i += 1
.
return 1
.
func isemirp n .
if isprim n = 0
return 0
.
m = n
while m > 0
d = m mod 10
m = m div 10
rev = rev * 10 + d
.
if rev = n
return 0
.
return isprim rev
.
m = 2
write "First 20 emirps: "
while cnt < 20
if isemirp m = 1
write m & " "
cnt += 1
.
m += 1
.
print ""
write "Emirps between 7700 8000: "
for m = 7700 to 8000
if isemirp m = 1
write m & " "
.
.
print ""
m = 2
cnt = 0
repeat
cnt += isemirp m
until cnt = 10000
m += 1
.
print "The 10000th emirp: " & m
</syntaxhighlight>
{{out}}
<pre>
First 20 emirps: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Emirps between 7700 8000: 7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
The 10000th emirp: 948349
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Emirp do
defp prime?(2), do: true
defp prime?(n) when n<2 or rem(n,2)==0, do: false
Line 711 ⟶ 929:
end
 
Emirp.task</langsyntaxhighlight>
 
{{out}}
Line 722 ⟶ 940:
=={{header|F_Sharp|F#}}==
===The function===
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functionThe_functions Extensible Prime Generator (F#)]
<langsyntaxhighlight lang="fsharp">
// Generate emirps. Nigel Galloway: November 19th., 2017
let emirp =
let rec fN n g = match n with |0->g |_->fN (n/10) (g*10+n%10)
let fG n g = n<>g && isPrime g
primesprimes32() |> Seq.filter (fun n -> fG n (fN n 0))
</syntaxhighlight>
</lang>
 
===The Task===
<langsyntaxhighlight lang="fsharp">
emirps |> (Seq.take 20) |> Seq.iter (printf "%d ")
</syntaxhighlight>
</lang>
{{out}}
<pre>
13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
</pre>
<langsyntaxhighlight lang="fsharp">
emirps |> Seq.skipWhile (fun n->n<7700) |> Seq.takeWhile (fun n->n<=8000) |> Seq.iter (printf "%d ")
</syntaxhighlight>
</lang>
{{out}}
<pre>
7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "%d" (Seq.item 9999 emirps)
</syntaxhighlight>
</lang>
{{out}}
<pre>
948349
</pre>
<langsyntaxhighlight lang="fsharp">
// count # of emirps with n = 2 to 7 digits. Nigel Galloway: August 8th., 2018
let n=emirp |> Seq.takeWhile(fun n->n<10000000) |> Seq.countBy(fun n->match n with |n when n>999999->7
Line 761 ⟶ 980:
|_ ->2)
for n,g in n do printfn "%d -> %d" n g
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 774 ⟶ 993:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: io kernel lists lists.lazy math.extras math.parser
math.primes sequences ;
FROM: prettyprint => . pprint ;
Line 804 ⟶ 1,023:
part1 nl part2 nl part3 ;
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 815 ⟶ 1,034:
10,000th emirp:
948349
</pre>
 
=={{header|Forth}}==
Keeps a pair of numbers on the stack to represent a generator. This generator approach means that all tasks start from the first Emirp (13), even task 2.
<syntaxhighlight lang="forth">
#! /usr/bin/gforth-fast
 
: reverse ( n -- n )
0 swap
begin
10 /mod >r swap 10 * +
r> dup 0= until drop ;
 
: 2^ 1 swap lshift ;
 
create 235-wheel 6 c, 4 c, 2 c, 4 c, 2 c, 4 c, 6 c, 2 c,
does> swap 7 and + c@ ;
 
0 1 2constant init-235 \ roll 235 wheel at position 1
2 11 2constant emirp-start \ starting position to roll wheel for emirp search.
 
: next-235 over 235-wheel + swap 1+ swap ;
 
\ check that n is prime excepting multiples of 2, 3, 5.
: sq dup * ;
: wheel-prime? ( n -- f )
>r init-235 begin
next-235
dup sq r@ > if rdrop 2drop true exit then
r@ over mod 0= if rdrop 2drop false exit then
again ;
 
: prime? ( n -- f )
dup 2 <
if drop false
else
dup 1 and 0=
if 2 =
else dup 3 mod 0=
if 3 =
else dup 5 mod 0=
if 5 =
else wheel-prime?
then
then
then
then ;
 
: emirp? ( n -- f )
dup reverse 2dup <>
swap prime? and
swap wheel-prime? and ;
 
: next-emirp ( m n -- m' n' )
begin
next-235
dup emirp? until ;
 
 
: task1
cr ." The first 20 emirps are: " 0 { count }
emirp-start begin
next-emirp dup .
count 1+ dup to count
20 = until 2drop ;
 
: task2
cr ." emirps between 7700 and 8000: "
emirp-start begin
next-emirp dup 7700 8000 within if dup . then
dup 8000 > until 2drop ;
 
: task3
cr ." The 10,000th emirp is " 0 { count }
emirp-start begin
next-emirp
count 1+ dup to count
10000 = until nip . ;
 
task1 task2 task3
cr bye
</syntaxhighlight>
{{Out}}
<pre>
The first 20 emirps are: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
emirps between 7700 and 8000: 7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
The 10,000th emirp is 948349
</pre>
 
Line 826 ⟶ 1,132:
For factoring numbers up to the 32-bit two's complement integer limit, the table need not be large, and it can easily enough be stored as a collection of sixteen and thirty-two bit numbers to save some space. Accessing an array PRIME(i) can be made a function GETPRIME(i) without a change in syntax (as needed in pascal: Prime[i] for an array, GetPrime(i) for a function), at least for reading. So, instead of 4792x4 = 19168 bytes, 12144 are needed, to set against the additional code complexity. These days, this is a difference of small importance. Actually, a further value is needed to hold Prime(4793) = 46349. Function ISPRIME does not determine its stepping point via the near universal usage of SQRT(n). If calculated in double precision this will give acceptable results for a 32-bit integer, but I have been burnt by an ad-hoc calculation nDgits = LOG10(x) + 1 failing for x = 10 because Log10(10) = 0·9999etc. which may well round to one, but truncates to zero. So, a SQRT-free demonstration, needed if the MOD function were unavailable. Actually, if P(i) is the last factor to be checked, this suffices up to the square of P(i + 1), not P(i). But this bound is only useful when successive numbers are being tested; for an individual factorisation it is too messy.
 
The initial version ran very slowly once past the first run, and this prompted some instrumentation, the addition of counters for the invocations. It transpired that GETPRIME(i) was being invoked thousands of millions of times... Once again, a N<sup>2</sup> process is to be avoided, here when NEXTPRIME(n) was stepping linearly along the array of primes (in the hope of knowing the next prime along without having to recalculate it) and being invoked many times to do so. This was fixed by introducing a binary search, the list of primes being of course in order. The early version of NEXTPRIME(n) also did not attempt to save new primes, as it might be invoked with a value well beyond the end of the table and the next value on from ''n'' might be past many lesser primes. But by working on from PRIME(NP) up to ''n'' they can be found and saved along the way. Saving new primes in NEXTPRIME meant that GETPRIME should no longer itself attempt saving, as it is invoking NEXTPRIME. Mutual recursion is all very well, but organisation is important also. <langsyntaxhighlight Fortranlang="fortran"> MODULE BAG !A mixed assortment.
INTEGER MSG !I/O unit number to share about.
INTEGER PF16LIMIT,PF32LIMIT,NP !Know that P(3512) = 32749, the last within two's complement 16-bit integers.
Line 999 ⟶ 1,305:
CALL EMIRP(10,10000,10000, 1,1000000) !Of three separate invocations.
 
END !Whee!</langsyntaxhighlight>
Output:
<pre>
Line 1,052 ⟶ 1,358:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function isPrime(n As UInteger) As Boolean
Line 1,113 ⟶ 1,419:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,126 ⟶ 1,432:
The 10,000th Emirp prime is : 948349
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">
isEmirp[x] :=
{
if isPrime[x]
{
s = toString[x]
rev = reverse[s]
return s != rev and isPrime[parseInt[rev]]
}
return false
}
 
// Functions that return finite and infinite enumerating expressions of emirps
emirps[] := select[primes[], getFunction["isEmirp", 1]]
emirps[begin, end] := select[primes[begin, end], getFunction["isEmirp", 1]]
 
println["First 20: " + first[emirps[], 20]]
println["Range: " + emirps[7700, 8000]]
println["10000th: " + last[first[emirps[], 10000]]]
</syntaxhighlight>
{{out}}
<pre>
First 20: [13, 17, 31, 37, 71, 73, 79, 97, 107, 113, 149, 157, 167, 179, 199, 311, 337, 347, 359, 389]
Range: [7717, 7757, 7817, 7841, 7867, 7879, 7901, 7927, 7949, 7951, 7963]
10000th: 948349
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn IsPrime( n as NSUInteger ) as BOOL
BOOL isPrime = YES
NSUInteger i
if n < 2 then exit fn = NO
if n = 2 then exit fn = YES
if n mod 2 == 0 then exit fn = NO
for i = 3 to int(n^.5) step 2
if n mod i == 0 then exit fn = NO
next
end fn = isPrime
 
 
local fn ReverseNumber( n as NSUInteger ) as NSUInteger
NSInteger sum = 0
if n < 10 then exit fn = n
while ( n > 0 )
sum = 10 * sum + ( n mod 10 )
n /= 10
wend
end fn = sum
 
 
local fn IsEmirp( n as NSUInteger ) as BOOL
BOOL result = NO
NSUInteger r = fn ReverseNumber(n)
if r != n and fn IsPrime(n) and fn IsPrime(r) then result = YES
end fn = result
 
 
local fn GetEmirpPrimes
NSUInteger count = 0, i = 13
printf @"\nThe first 20 Emirp primes are:"
do
if fn IsEmirp(i) then printf @"%4lu\b", i : count++
i += 2
until ( count == 20 )
printf @"\n\nThe Emirp primes between 7700 and 8000 are:"
i = 7701
while ( i < 8000 )
if fn IsEmirp(i) then printf @"%5lu\b", i
i += 2
wend
i = 13 : count = 0
while (1)
if fn IsEmirp(i) then count++
if count = 10000 then exit while
i += 2
wend
printf @"\n\nThe 10,000th Emirp prime is: %lu", i
end fn
 
fn GetEmirpPrimes
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
The first 20 Emirp primes are:
13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
 
The Emirp primes between 7700 and 8000 are:
7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
 
The 10,000th Emirp prime is: 948349
</pre>
 
 
=={{header|Go}}==
Line 1,131 ⟶ 1,540:
 
As a side note, by using the same API as the prime number generator this also demonstrates how Go interfaces can be used (and note it doesn't require the existing code/package to know anything about the interface being defined).
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,314 ⟶ 1,723:
fmt.Println()
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,338 ⟶ 1,747:
948349
</pre>
 
=={{header|Groovy}}==
{{trans|Java}}
<syntaxhighlight lang="groovy">class Emirp {
 
//trivial prime algorithm, sub in whatever algorithm you want
static boolean isPrime(long x) {
if (x < 2) return false
if (x == 2) return true
if ((x & 1) == 0) return false
 
for (long i = 3; i <= Math.sqrt(x); i += 2) {
if (x % i == 0) return false
}
 
return true
}
 
static boolean isEmirp(long x) {
String xString = Long.toString(x)
if (xString.length() == 1) return false
if (xString.matches("[24568].*") || xString.matches(".*[24568]")) return false //eliminate some easy rejects
long xR = Long.parseLong(new StringBuilder(xString).reverse().toString())
if (xR == x) return false
return isPrime(x) && isPrime(xR)
}
 
static void main(String[] args) {
int count = 0
long x = 1
 
println("First 20 emirps:")
while (count < 20) {
if (isEmirp(x)) {
count++
print(x + " ")
}
x++
}
 
println("\nEmirps between 7700 and 8000:")
for (x = 7700; x <= 8000; x++) {
if (isEmirp(x)) {
print(x + " ")
}
}
 
println("\n10,000th emirp:")
x = 1
count = 0
for (; count < 10000; x++) {
if (isEmirp(x)) {
count++
}
}
//--x to fix the last increment from the loop
println(--x)
}
}</syntaxhighlight>
{{out}}
<pre>First 20 emirps:
13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Emirps between 7700 and 8000:
7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
10,000th emirp:
948349</pre>
 
=={{header|Haskell}}==
Line 1,345 ⟶ 1,820:
{{Works with|primes|0.2.1.0}}
 
<langsyntaxhighlight lang="haskell">#!/usr/bin/env runghc
 
import Data.HashSet (HashSet, fromList, member)
Line 1,420 ⟶ 1,895:
"slice" -> print $ emirpSlice lo hi
"values" -> print $ emirpValues lo hi
_ -> usage</langsyntaxhighlight>
 
{{out}}
This program uses the same format for command line arguments as the Perl 6Raku example.
 
<pre>
Line 1,436 ⟶ 1,911:
===List-based===
Using list-based incremental sieve from [[Sieve_of_Eratosthenes#With_Wheel|here]] and trial division from [[Primality_by_trial_division#Haskell|here]],
<langsyntaxhighlight lang="haskell"> λ> let emirp p = let q=(read.reverse.show) p in q /= p && noDivsBy primesW q
 
λ> take 20 . filter emirp $ primesW
Line 1,445 ⟶ 1,920:
 
λ> (!! (10000-1)) . filter emirp $ primesW
948349 -- 0.69 secs</langsyntaxhighlight>
 
=={{header|J}}==
 
'''Solution''':<langsyntaxhighlight lang="j"> emirp =: (] #~ ~: *. 1 p: ]) |.&.:":"0 NB. Input is array of primes</langsyntaxhighlight>
 
In other words: select numbers from the argument list whose decimal reverse is both different and prime and return those decimal reversed values as numbers. (For simplicity, we require that our argument be a list of prime numbers.)
 
'''Examples'''<langsyntaxhighlight lang="j"> /:~ emirp p: 2+i.75
13 17 31 37 71 73 79 97 113 311 701 733 743 751 761 941 953 971 983 991
 
Line 1,466 ⟶ 1,941:
NB. alternative approach (first emirp value would be at index 0):
9999 { /:~ emirp p:i.1e5
943849</langsyntaxhighlight>
 
=={{header|Java}}==
This implementation uses a slight optimization discussed in the talk page. It will not actually check the primality (forwards or backwards) for a number that starts or ends with the digits 2, 4, 5, 6, or 8 since no primes greater than 7 end with those digits.
<langsyntaxhighlight lang="java">public class Emirp{
//trivial prime algorithm, sub in whatever algorithm you want
Line 1,523 ⟶ 1,998:
System.out.println(--x);
}
}</langsyntaxhighlight>
{{out}}
<pre>First 20 emirps:
Line 1,530 ⟶ 2,005:
7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
10,000th emirp:
948349</pre>
 
=={{header|JavaScript}}==
Script source
<syntaxhighlight lang="javascript">function isPrime(n) {
if (!(n % 2) || !(n % 3)) return 0;
 
var p = 1;
while (p * p < n) {
if (n % (p += 4) == 0 || n % (p += 2) == 0) {
return false
}
}
return true
}
 
function isEmirp(n) {
var s = n.toString();
var r = s.split("").reverse().join("");
return r != n && isPrime(n) && isPrime(r);
}
 
function main() {
var out = document.getElementById("content");
 
var c = 0;
var x = 11;
var last;
var str;
 
while (c < 10000) {
if (isEmirp(x)) {
c += 1;
 
// first twenty emirps
if (c == 1) {
str = "<p>" + x;
}
else if (c < 20) {
str += " " + x;
}
else if (c == 20) {
out.innerHTML = str + " " + x + "</p>";
}
 
// all emirps between 7,700 and 8,000
else if (7700 <= x && x <= 8001) {
if (last < 7700) {
str = "<p>" + x;
} else {
str += " " + x;
}
}
else if (x > 7700 && last < 8001) {
out.innerHTML += str + "</p>";
}
 
// the 10,000th emirp
else if (c == 10000) {
out.innerHTML += "<p>" + x + "</p>";
}
 
last = x;
}
x += 2;
}
}
</syntaxhighlight>
 
Solution page
<syntaxhighlight lang="html"><!DOCTYPE html>
<html>
<head>
<title>Emirp primes</title>
<script src="emirp.js"></script>
</head>
<body onload="main()">
<div id="content"></div>
</body>
</html></syntaxhighlight>
{{out}}
<pre>13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
948349</pre>
 
Line 1,540 ⟶ 2,098:
 
'''Infrastructure: prime numbers'''
<langsyntaxhighlight lang="jq">def is_prime:
if . == 2 then true
else
Line 1,571 ⟶ 2,129:
| until( relatively_prime ; .[0] += 2) as $nextp
| ( $previous + [$nextp[0]] );
2, ([2,3] | recurse( next ) | .[-1]) ;</langsyntaxhighlight>
 
'''Emirps'''
<langsyntaxhighlight lang="jq">def is_emirp:
. as $n
| tostring | explode | reverse | implode | tonumber | (. != $n) and is_prime ;
Line 1,586 ⟶ 2,144:
else if ($p | is_emirp) then [.[0] + 1, $p] else .[1] = null end
end;
if .[1] then . else empty end ) ;</langsyntaxhighlight>
 
'''The tasks'''
 
(0) The three separate subtasks can be accomplished in one step as follows:
<langsyntaxhighlight lang="jq">emirps(10000)
| select( .[0] <= 20 or (7700 <= .[1] and .[1] <= 8000) or .[0] == 10000)</langsyntaxhighlight>
 
The output of the above is shown below.
Line 1,599 ⟶ 2,157:
 
(1) First twenty:
<syntaxhighlight lang ="jq">emirps(20)</langsyntaxhighlight>
 
(2) Selection by value
<syntaxhighlight lang="text">label $top
| primes
| if (7700 <= .) and (. <= 8000) and is_emirp then .
elif . > 8000 then break $top
else empty
end</langsyntaxhighlight>
 
(3) 10,000th
<syntaxhighlight lang="text">last(emirps(10000)) | .[1]</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang="sh">$ jq -c -n -f Emirp_primes.jq
[1,13]
[2,17]
Line 1,645 ⟶ 2,203:
[189,7951]
[190,7963]
[10000,948349]</langsyntaxhighlight>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using Primes
{{works with|Julia|0.6}}
 
<lang julia>using Primes
 
function collapse(n::Array{<:Integer})
Line 1,661 ⟶ 2,217:
 
Base.reverse(n::Integer) = collapse(reverse(digits(n)))
isemirp(n::Integer) = (if isprime(n) m = reverse(n); return m != n && isprime(reverse(nm) end; false)
 
function firstnemirps(m::Integer)
rst = Array{zeros(typeof(m)}(, m)
i, n = 1, 2
@inbounds while i ≤ m
if isemirp(n)
rst[i] = n
Line 1,679 ⟶ 2,235:
println("First 20:\n", emirps[1:20])
println("Between 7700 and 8000:\n", filter(x -> 7700 ≤ x ≤ 8000, emirps))
println("10000th:\n", emirps[10000])</lang>
</syntaxhighlight>{{out}}
 
<pre>
{{out}}
<pre>First 20:
[213, 317, 531, 737, 1171, 1373, 1779, 3197, 37107, 71113, 73149, 79157, 97167, 101179, 107199, 113311, 131337, 149347, 151359, 157389]
Between 7700 and 8000:
[7717, 7757, 7817, 7841, 7867, 7879, 7901, 7927, 7949, 7951, 7963]
10000th:
948349
942569</pre>
</pre>
 
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="scala">// version 1.1.4
 
fun isPrime(n: Int) : Boolean {
Line 1,757 ⟶ 2,314:
while(true)
print(i)
}</langsyntaxhighlight>
 
{{out}}
Line 1,769 ⟶ 2,326:
The 10,000th Emirp prime is : 948349
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def prime
{def prime.r
{lambda {:m :n}
{if {> {* :m :m} :n}
then :n
else {if {= {% :n :m} 0}
then false
else {prime.r {+ :m 1} :n}}
}}}
{lambda {:n}
{prime.r 2 :n}
}}
-> prime
 
{def emirp
{lambda {:n}
{let { {:n :n}
{:p {prime :n}}
{:q {prime {W.reverse :n}}}
} {if {and {not {= :p :q}}
{not :p .}
{not :q .} }
then :n
else .}}}}
-> emirp
 
{def emirps
{def emirps.loop
{lambda {:n :m :a :i :j}
{if {or {>= :j :n} {> :i :m}}
then :a with :i tests
else {emirps.loop :n :m
{if {W.equal? {emirp :i} :i}
then {A.addlast! :i :a} {+ :i 2} {+ :j 1}
else :a {+ :i 2} :j}}
}}}
{lambda {:i :n :m}
{emirps.loop :n :m {A.new} :i 0}
}}
-> emirps
 
{emirps 13 20 500}
-> [13,17,31,37,71,73,79,97,107,113,149,157,167,179,199,311,337,347,359,389] with 391 tests
 
{emirps 7701 11 10000}
-> [7717,7757,7817,7841,7867,7879,7901,7927,7949,7951,7963] with 7965 tests
 
{emirps 948300 10 1000000}
-> {emirps 948300 10 1000000} // stackoverflow
 
{emirp 948349}
-> 948349
 
</syntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
function isPrime (n)
if n < 2 then return false end
Line 1,813 ⟶ 2,427:
print("Wrong number of arguments")
end
</syntaxhighlight>
</lang>
Command prompt session:
<pre>
Line 1,827 ⟶ 2,441:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">EmirpPrime := proc(n)
local eprime;
eprime := parse(StringTools:-Reverse(convert(n,string)));
Line 1,849 ⟶ 2,463:
EmirpPrime~([seq(7700..8000)]);
EmirpsList(10000)[-1];
</syntaxhighlight>
</lang>
{{out}}
<pre>[13, 17, 31, 37, 71, 73, 79, 97, 107, 113, 149, 157, 167, 179, 199, 311, 337, 347, 359, 389]
Line 1,855 ⟶ 2,469:
948349</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
First a simple helper function
<langsyntaxhighlight Mathematicalang="mathematica">reverseDigits[n_Integer] := FromDigits@Reverse@IntegerDigits@n</langsyntaxhighlight>
A function to test whether n is an emirp prime
<langsyntaxhighlight Mathematicalang="mathematica">emirpQ[n_Integer] :=
Block[{rev = reverseDigits@n}, And[n != rev, PrimeQ[rev]]]</langsyntaxhighlight>
Note, this test function assumes n is prime. Adding a check to verify n is prime will have
an impact on execution time for finding the mth emirp prime particularly when m is large.
 
Finally, a function which returns the first emirp prime larger than the supplied argument
<langsyntaxhighlight Mathematicalang="mathematica">nextEmirp[n_Integer] :=
NestWhile[NextPrime, NextPrime[n], ! emirpQ[#] &]</langsyntaxhighlight>
 
With these the first 20 emirp primes are computed as:
<langsyntaxhighlight Mathematicalang="mathematica">Rest@NestList[nextEmirp, 1, 20]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,875 ⟶ 2,489:
 
The emirp primes betweewn 7700 and 8000 are:
<langsyntaxhighlight Mathematicalang="mathematica">Rest@NestWhileList[nextEmirp, 7700, # < 8000 &]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,881 ⟶ 2,495:
 
The 10,000th emirp prime is:
<syntaxhighlight lang Mathematica="mathematica">Nest[nextEmirp, 1, 10000]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,887 ⟶ 2,501:
 
=={{header|MATLAB}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
NN=(1:1:1e6); %Natural numbers between 1 and t
pns=NN(isprime(NN)); %prime numbers
Line 1,893 ⟶ 2,507:
a=pns(isprime(p)); b=p(isprime(p)); c=a-b;
emirps=NN(a(c~=0));
</syntaxhighlight>
</lang>
{{out}}
<pre>the first twenty emirps are: emirps(1:20)
Line 1,923 ⟶ 2,537:
948349
</pre>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Emirp;
FROM Conversions IMPORT StrToLong;
FROM FormatString IMPORT FormatString;
Line 2,030 ⟶ 2,645:
 
ReadChar
END Emirp.</langsyntaxhighlight>
 
=={{header|OforthNim}}==
===Using a simple test of primality===
This is not the most efficient way to solve the tasks, but it doesn’t set a limit ''a priori''. We have done some optimizations to speed up the primality test. Using a cache didn’t improve the times. The program runs in about 100 ms.
<syntaxhighlight lang="nim">import math
 
# Increments to find the next divisor when testing primality.
const Incr = [4, 2, 4, 2, 4, 6, 2, 6]
 
#---------------------------------------------------------------------------------------------------
 
func reversed(n: int): int =
## Return the reversed number in base 10 representation.
var n = n
while true:
result = 10 * result + n mod 10
n = n div 10
if n == 0:
break
 
#---------------------------------------------------------------------------------------------------
 
func isPrime(n: int): bool =
## Check if a number is prime.
## We are already sure that "n" is not a multiple of 2, 3 or 5,
## so we don’t check the modulo.
var k = 7
var i = 0
while k <= int(sqrt(n.toFloat)):
if n mod k == 0:
return false
inc k, Incr[i]
i = if i == Incr.high: 0 else: i + 1
result = true
 
#---------------------------------------------------------------------------------------------------
 
iterator emirps(): int =
## Yield the emirps.
var n = 13
var i = 2 # Current index in the increment array.
while true:
# We find the reversed number first as it allows to eliminate candidates.
let r = reversed(n)
if r != n and r mod 10 in [1, 3, 7, 9] and n.isPrime and r.isPrime:
yield n
inc n, Incr[i]
i = if i == Incr.high: 0 else: i + 1
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
stdout.write "First 20 emirps:"
var count = 0
for n in emirps():
stdout.write ' ', n
inc count
if count == 20:
echo ""
break
 
stdout.write "Emirps between 7700 and 8000:"
for n in emirps():
if n in 7700..8000:
stdout.write ' ', n
elif n > 8000:
echo ""
break
 
stdout.write "The 10000th emirp: "
count = 0
for n in emirps():
inc count
if count == 10000:
echo n
break</syntaxhighlight>
 
{{out}}
<pre>First 20 emirps: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Emirps between 7700 and 8000: 7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
The 10000th emirp: 948349</pre>
 
===Using a sieve of Erathostenes===
The sieve is a simple one, with no optimization to reduce its size. As it is a non-extensible sieve, there is a limit. So, in task 3, we check if the sieve size must be increased. The program runs in about 6 ms.
 
<syntaxhighlight lang="nim">import math
 
const N = 1_000_000
 
# Sieve of Erathostenes.
var isPrime: array[2..N, bool]
for item in isPrime.mitems: item = true
 
# Initialize the sieve.
for n in 2..int(sqrt(N.toFloat)):
if isPrime[n]:
for k in countup(n * n, N, n):
isPrime[k] = false
 
#---------------------------------------------------------------------------------------------------
 
func reversed(n: int): int =
## Return the reversed number in base 10 representation.
var n = n
while true:
result = 10 * result + n mod 10
n = n div 10
if n == 0:
break
 
#---------------------------------------------------------------------------------------------------
 
iterator emirps(): int =
## Yield the emirps.
for n, prime in isPrime:
if prime:
let r = reversed(n)
if r > N:
break # Unable to continue.
if r != n and isPrime[r]:
yield n
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
stdout.write "First 20 emirps:"
var count = 0
for n in emirps():
stdout.write ' ', n
inc count
if count == 20:
echo ""
break
 
stdout.write "Emirps between 7700 and 8000:"
for n in emirps():
if n in 7700..8000:
stdout.write ' ', n
elif n > 8000:
echo ""
break
 
stdout.write "The 10000th emirp: "
count = 0
for n in emirps():
inc count
if count == 10000:
echo n
break
if count < 10000:
echo "Not enough primes. Increase value of N."</syntaxhighlight>
 
{{out}}
<pre>First 20 emirps: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Emirps between 7700 and 8000: 7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
The 10000th emirp: 948349</pre>
 
=={{header|OCaml}}==
Using the function <code>seq_primes</code> from [[Extensible prime generator#OCaml]]:
<syntaxhighlight lang="ocaml">let int_reverse =
let rec loop m n =
if n < 10 then m + n else loop ((m + n mod 10) * 10) (n / 10)
in loop 0
 
let is_prime n =
let not_divisible x = n mod x <> 0 in
seq_primes |> Seq.take_while (fun x -> x * x <= n) |> Seq.for_all not_divisible
 
let seq_emirps =
let is_emirp n = let m = int_reverse n in m <> n && is_prime m in
seq_primes |> Seq.filter is_emirp
 
let () =
let seq_show sq = print_newline (Seq.iter (Printf.printf " %u") sq) in
seq_emirps |> Seq.take 20 |> seq_show;
seq_emirps |> Seq.drop_while ((>) 7700) |> Seq.take_while ((>) 8000) |> seq_show;
seq_emirps |> Seq.drop 9999 |> Seq.take 1 |> seq_show</syntaxhighlight>
{{out}}
<pre>
13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
948349
</pre>
 
=={{header|Oforth}}==
Using isPrime function of Primality by trial division task :
 
<langsyntaxhighlight Oforthlang="oforth">: isEmirp(n)
n isPrime ifFalse: [ false return ]
n asString reverse asInteger dup n == ifTrue: [ drop false ] else: [ isPrime ] ;
Line 2,047 ⟶ 2,842:
dup isEmirp ifTrue: [ dup l add ] 1 +
]
drop l ;</langsyntaxhighlight>
 
{{out}}
Line 2,062 ⟶ 2,857:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">rev(n)=subst(Polrev(digits(n)),'x,10);
emirp(n)=my(r=rev(n)); isprime(r) && isprime(n) && n!=r
select(emirp, primes(100))[1..20]
select(emirp, primes([7700,8000]))
s=10000; forprime(p=2,,if(emirp(p) && s--==0, return(p)))</langsyntaxhighlight>
{{out}}
<pre>%1 = [13, 17, 31, 37, 71, 73, 79, 97, 107, 113, 149, 157, 167, 179, 199, 311, 337, 347, 359, 389]
Line 2,076 ⟶ 2,871:
using trial division unit , but jumping over number ranges, where the reversed numbers can't be a prime.
Compiles with Delphi and Free Pascal.
<langsyntaxhighlight lang="pascal">program Emirp;
//palindrome prime 13 <-> 31
{$IFDEF FPC}
Line 2,324 ⟶ 3,119:
OutPutHelp;
end;
End.</langsyntaxhighlight>
;output:
<pre>
Line 2,365 ⟶ 3,160:
=={{header|Perl}}==
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use feature 'say';
use ntheory qw(forprimes is_prime);
 
Line 2,387 ⟶ 3,182:
forprimes { print " $_" if is_prime(reverse $_) && $_ ne reverse($_) } 7700,8000;
print "\n";
say "The 10_000'th emirp: ", (emirp_list(10000))[-1];</langsyntaxhighlight>
{{out}}
<pre>First 20: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Line 2,393 ⟶ 3,188:
The 10_000'th emirp: 948349</pre>
 
=={{header|Perl 6Phix}}==
Does not assume anywhere that some pre-guessed value will be enough.
{{Works with|Rakudo|2018.10}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
For better performance, build the lazy list using module <code>Math::Primesieve</code>, not the built-in, then display results based on parameters passed in. The default is to display an array slice starting and stopping at the given indices. Alternately, ask for all values between two endpoints.
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">emirps</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">rev</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">*</span><span style="color: #000000;">10</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">emirp</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rev</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">n</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">true</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">usage</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"use a single command line argument, with no spaces, eg \"1-20\" (first 20), \n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\"7700..8000\" (between 7700 and 8000), or \"10000\" (the 10,000th).\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">abort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">arg3</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">args</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'-'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">arg3</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- nth to mth emirp range</span>
<span style="color: #000000;">args</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">arg3</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d-%d"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">args</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #000000;">usage</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #0000FF;">{{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">}}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">args</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">emirps</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">m</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">emirp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">emirps</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">k</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">k</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"emirps %d to %d: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">emirps</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">..</span><span style="color: #000000;">m</span><span style="color: #0000FF;">]})</span>
<span style="color: #008080;">elsif</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #008000;">".."</span><span style="color: #0000FF;">,</span><span style="color: #000000;">arg3</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- emirps between n amd m</span>
<span style="color: #000000;">args</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">arg3</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d..%d"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">args</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #000000;">usage</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #0000FF;">{{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">}}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">args</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">emirps</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #000000;">emirps</span><span style="color: #0000FF;">[$]<</span><span style="color: #000000;">m</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">emirp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">emirps</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">k</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">k</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">emirps</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">emirps</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]></span><span style="color: #000000;">n</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">i</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">emirps</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">emirps</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]></span><span style="color: #000000;">m</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"emirps between %d and %d: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">emirps</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">..</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]})</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">else</span> <span style="color: #000080;font-style:italic;">-- nth emirp</span>
<span style="color: #000000;">args</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">arg3</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">args</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #000000;">usage</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #0000FF;">{{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">}}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">args</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">emirps</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">emirp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">emirps</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">k</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">k</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"emirp %d: %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">emirps</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">]})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">cl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">command_line</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cl</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">2</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1-20"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"7700..8000"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"10000"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">elsif</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cl</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">3</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cl</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">usage</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
emirps 1 to 20: {13,17,31,37,71,73,79,97,107,113,149,157,167,179,199,311,337,347,359,389}
emirps between 7700 and 8000: {7717,7757,7817,7841,7867,7879,7901,7927,7949,7951,7963}
emirp 10000: 938033
</pre>
 
=={{header|PHP}}==
<lang perl6>use Math::Primesieve;
 
<syntaxhighlight lang="php"><?php
sub prime-hash (Int $max) {
my $sieve = Math::Primesieve.new;
my @primes = $sieve.primes($max);
@primes.Set;
}
 
function is_prime($n) {
sub MAIN ($start, $stop = Nil, $display = <slice>) {
myif ($endn <= $stop3) // $start;{
my %primes = prime-hash(100* return $end)n > 1;
my} @emirpselseif =(($n lazy% gather2 for== 10) .. * ->or ($n % 3 == 0)) {
return false;
take $n if %primes{$n} and %primes{$n.flip} and $n != $n.flip
}
$i = 5;
 
givenwhile ($displayi * $i <= $n) {
whenif 'slice'($n % { return @emirps[$start-1i ..== $end-1]0) };{
when 'values' { return false;
my @values = gather for @emirps {
.take if $start < $_ < $end;
last if $_> $end
}
return @values
}
$i += 2;
if ($n % $i == 0) {
return false;
}
$i += 4;
}
return true;
}</lang>
}
{{out}}
Run with passed parameters: 1 20
 
function is_emirp($n) {
('slice' is the default. you <i>could</i> pass it in, but it isn't necessary.)
$r = (int) strrev((string) $n);
<pre>13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389</pre>
return (($r != $n) and is_prime($r) and is_prime($n));
Run with passed parameters: 7700 8000 values
}
<pre>7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963</pre>
Run with passed parameter: 10000
<pre>948349</pre>
 
$c = $x = 0;
=={{header|Phix}}==
$first20 = $between = '';
Using [[Extensible_prime_generator#Phix]], not that this task makes trial division onerous.<br>
do {
Does not assume anywhere that some pre-guessed value will be enough.
$x++;
<lang Phix>sequence primes = {2,3,5,7}
if (is_emirp($x)) {
atom sieved = 10
$c++;
if ($c <= 20) {
$first20 .= $x . ' ';
}
if (7700 <= $x and $x <= 8000) {
$between .= $x . ' ';
}
}
} while ($c < 10000);
 
echo
procedure add_block()
'First twenty emirps :', PHP_EOL, $first20, PHP_EOL,
integer N = min((sieved-1)*sieved,400000)
'Emirps between 7,700 and 8,000 :', PHP_EOL, $between, PHP_EOL,
sequence sieve = repeat(1,N) -- sieve[i] is really i+sieved
'The 10,000th emirp :', PHP_EOL, $x, PHP_EOL;</syntaxhighlight>
for i=2 to length(primes) do -- (evens filtered on output)
atom p = primes[i], p2 = p*p
if p2>sieved+N then exit end if
if p2<sieved+1 then
p2 += ceil((sieved+1-p2)/p)*p
end if
p2 -= sieved
if and_bits(p2,1)=0 then p2 += p end if
for k=p2 to N by p*2 do
sieve[k] = 0
end for
end for
for i=1 to N by 2 do
if sieve[i] then
primes &= i+sieved
end if
end for
sieved += N
end procedure
 
{{out}}
function is_prime(integer n)
<pre>First twenty emirps :
while sieved<n do
13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
add_block()
Emirps between 7,700 and 8,000 :
end while
7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
return binary_search(n,primes)>0
The 10,000th emirp :
end function
948349</pre>
 
sequence emirps = {}
 
function rev(integer n)
integer res = 0
while n do
res = res*10+remainder(n,10)
n = floor(n/10)
end while
return res
end function
 
function emirp(integer n)
if is_prime(n) then
integer r = rev(n)
if r!=n and is_prime(r) then
return 1
end if
end if
return 0
end function
 
procedure usage()
printf(1,"use a single command line argument, with no spaces, eg \"1-20\" (first 20), \n")
printf(1,"\"7700..8000\" (between 7700 and 8000), or \"10000\" (the 10,000th).\n")
{} = wait_key()
abort(0)
end procedure
 
procedure main(string arg3)
sequence args
integer n,m
if find('-',arg3) then -- nth to mth emirp range
args = scanf(arg3,"%d-%d")
if length(args)!=1 then usage() end if
{{n,m}} = args
integer k = 1
while length(emirps)<m do
if emirp(k) then emirps &= k end if
k += 1
end while
printf(1,"emirps %d to %d: ",{n,m})
?emirps[n..m]
elsif match("..",arg3) then -- emirps between n amd m
args = scanf(arg3,"%d..%d")
if length(args)!=1 then usage() end if
{{n,m}} = args
integer k = 1
while length(emirps)=0 or emirps[$]<m do
if emirp(k) then emirps &= k end if
k += 1
end while
sequence s = {}
for i=1 to length(emirps) do
if emirps[i]>n then
for j=i to length(emirps) do
if emirps[j]>m then
printf(1,"emirps between %d and %d: ",{n,m})
?emirps[i..j-1]
exit
end if
end for
exit
end if
end for
else -- nth emirp
args = scanf(arg3,"%d")
if length(args)!=1 then usage() end if
{{n}} = args
integer k = 1
while length(emirps)<n do
if emirp(k) then emirps &= k end if
k += 1
end while
printf(1,"emirp %d: ",{n})
?emirps[n]
end if
end procedure
 
sequence cl = command_line()
if length(cl)=2 then
main("1-20")
main("7700..8000")
main("10000")
elsif length(cl)!=3 then
usage()
else
main(cl[3])
end if
{} = wait_key()</lang>
{{Out}}
<pre>
emirps 1 to 20: {13,17,31,37,71,73,79,97,107,113,149,157,167,179,199,311,337,347,359,389}
emirps between 7700 and 8000: {7717,7757,7817,7841,7867,7879,7901,7927,7949,7951,7963}
emirp 10000: 938033
</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de prime? (N)
(and
(bit? 1 N)
Line 2,601 ⟶ 3,378:
(println (take1 20))
(println (take2))
(println (take3))</langsyntaxhighlight>
{{out}}
<pre>(13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389)
Line 2,608 ⟶ 3,385:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process or(!);
pt1: Proc(run) Options(main);
/*********************************************************************
Line 2,771 ⟶ 3,548:
End;
 
End;</langsyntaxhighlight>
 
{{out}}
Line 2,791 ⟶ 3,568:
 
There is no explicit hard-coded ceiling added to the code for the prime generator, which is the reason given for the need to invoke a program three times in the task description.
<langsyntaxhighlight lang="python">from __future__ import print_function
from prime_decomposition import primes, is_prime
from heapq import *
Line 2,817 ⟶ 3,594:
if pr >= 7700: print(pr, end=', ')
print(']')
print('10000th:\n ', list(islice(emirp(), 10000-1, 10000)))</langsyntaxhighlight>
 
{{out}}
Line 2,826 ⟶ 3,603:
10000th:
[948349]</pre>
 
=={{header|Quackery}}==
 
<code>eratosthenes</code> and <code>isprime</code> are defined at [[Sieve of Eratosthenes#Quackery]].
 
<syntaxhighlight lang="quackery"> 1000000 eratosthenes
[ [] swap
[ dup 0 != while
10 /mod
rot swap join swap
again ]
swap
witheach
[ dip [ 10 * ] + ] ] is revnum ( n --> n )
[ dup isprime not iff
[ drop false ] done
dup revnum tuck = iff
[ drop false ] done
isprime ] is emirp ( n --> b )
[] 0
[ 1+ dup emirp if
[ tuck join swap ]
over size 20 = until ]
drop
echo cr
[] 7700
[ 1+ dup emirp if
[ tuck join swap ]
dup 8000 = until ]
drop
echo cr
0 0
[ 1+ dup emirp if
[ dip 1+ ]
over 10000 = until ]
nip echo cr</syntaxhighlight>
 
{{out}}
 
<pre>[ 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389 ]
[ 7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963 ]
948349</pre>
 
=={{header|R}}==
<syntaxhighlight lang="rsplus">
library(gmp)
 
emirp <- function(start = 1, end = Inf, howmany = Inf, ignore = 0) {
count <- 0
p <- start
 
while (count<howmany+ignore && p <= end) {
p <- nextprime(p)
p_reverse <- as.bigz(paste0(rev(unlist(strsplit(as.character(p), ""))), collapse = ""))
if (p != p_reverse && isprime(p_reverse) > 0) {
if (count >= ignore) cat(as.character(p)," ",sep="")
count <- count + 1
}
}
cat("\n")
}
cat("First 20 emirps: ")
emirp(howmany = 20)
 
cat("Emirps between 7700 and 8000: ")
emirp(start = 7700, end = 8000)
 
cat("The 10000th emirp: ")
emirp(ignore = 9999, howmany = 1)
</syntaxhighlight>
{{out}}
<pre>
First 20 emirps: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Emirps between 7700 and 8000: 7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
The 10000th emirp: 948349
</pre>
 
=={{header|Racket}}==
Line 2,838 ⟶ 3,694:
basic functions, unburdened by accounting or (too many) performance
considerations (please don't mark this as needing attention... I know it falls short of
<langsyntaxhighlight lang="racket">#lang racket
(require math/number-theory)
 
Line 2,858 ⟶ 3,714:
(let loop ((i 10000) (p 9))
(define p+2 (+ p 2))
(cond [(not (emirp-prime? p+2)) (loop i p+2)] [(= i 1) p+2] [else (loop (- i 1) p+2)]))</langsyntaxhighlight>
 
The second is somewhat larger and seems to be a playground for all sorts of code.
<langsyntaxhighlight lang="racket">#lang racket
;; ---------------------------------------------------------------------------------------------------
;; There are two distinct requirements here...
Line 3,005 ⟶ 3,861:
(check-equal? (time (task2 emirp-prime?/sieve)) (time (task2)))
(check-equal? (time (task3 emirp-prime?/sieve extend-sieve!)) (time (task3))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,028 ⟶ 3,884:
948349
Sieve size: 999998</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|Rakudo|2018.10}}
For better performance, build the lazy list using module <code>Math::Primesieve</code>, not the built-in, then display results based on parameters passed in. The default is to display an array slice starting and stopping at the given indices. Alternately, ask for all values between two endpoints.
 
<syntaxhighlight lang="raku" line>use Math::Primesieve;
 
sub prime-hash (Int $max) {
my $sieve = Math::Primesieve.new;
my @primes = $sieve.primes($max);
@primes.Set;
}
 
sub MAIN ($start, $stop = Nil, $display = <slice>) {
my $end = $stop // $start;
my %primes = prime-hash(100*$end);
my @emirps = lazy gather for 1 .. * -> $n {
take $n if %primes{$n} and %primes{$n.flip} and $n != $n.flip
}
 
given $display {
when 'slice' { return @emirps[$start-1 .. $end-1] };
when 'values' {
my @values = gather for @emirps {
.take if $start < $_ < $end;
last if $_> $end
}
return @values
}
}
}</syntaxhighlight>
{{out}}
Run with passed parameters: 1 20
 
('slice' is the default. you <i>could</i> pass it in, but it isn't necessary.)
<pre>13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389</pre>
Run with passed parameters: 7700 8000 values
<pre>7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963</pre>
Run with passed parameter: 10000
<pre>948349</pre>
 
=={{header|REXX}}==
Line 3,038 ⟶ 3,935:
<br>memoization was added (assisting with the <big>√{{overline|&nbsp;j&nbsp;}}</big>), &nbsp; and some of the trial divisions were hard-coded to minimize
<br>the CPU time a bit.
<langsyntaxhighlight lang="rexx">/*REXX program finds emirp primes (base 10): when a prime reversed, is another prime.*/
parse arg x y . /*obtain optional arguments from the CL*/
if x=='' | x=="," then do; x=1; y=20; end /*Not specified? Then use the default.*/
Line 3,073 ⟶ 3,970:
/* [↓] display the emirp list. */
say strip($); say; n=words($); ?=(n\==1) /*display the emirp primes wanted. */
if ? then say n 'emirp primes shown.' /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; when using the following for input: &nbsp; <tt> 1 &nbsp; 20 </tt>
<pre>
Line 3,092 ⟶ 3,989:
 
===version 2===
<langsyntaxhighlight lang="rexx"> /*********************************************************************
* 27.03.2014 Walter Pachl
*********************************************************************/
Line 3,218 ⟶ 4,115:
Say l
End
Return</langsyntaxhighlight>
'''output'''<pre>rexx ptz 1
the first 20 emirps:
Line 3,241 ⟶ 4,138:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
nr = 1
m = 2
Line 3,290 ⟶ 4,187:
next
return true
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
This program uses the words <code>RVSTR</code> and <code>BPRIM?</code>, respectively made to [[Reverse_a_string#RPL|revert a string]] and to [[Primality_by_trial_division#RPL|test primality by trial division]]. Requirement 3 of the task needs too much execution time to be allowed by the emulator watchdog timer.
{{works with|Halcyon Calc|4.2.7}}
≪ 0 SWAP
IF DUP R→B '''BPRIM?''' THEN
→STR DUP '''RVSTR'''
IF DUP ROT ≠ THEN STR→ R→B '''BPRIM?''' OR DUP END
END DROP
≫ ''''BMIRP?'''' STO
 
≪ { } 13 WHILE OVER SIZE 20 < REPEAT
IF DUP '''BMIRP?''' THEN DUP ROT SWAP + SWAP END
2 +
END DROP
{ } 7700 8000 FOR n
IF n '''BMIRP?''' THEN n + END
NEXT
≫ EVAL
{{out}}
<pre>
2: { 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389 }
1: { 7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963 }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'prime'
 
emirp = Enumerator.new do |y|
Line 3,310 ⟶ 4,231:
break
end
end</langsyntaxhighlight>
 
{{out}}
Line 3,323 ⟶ 4,244:
 
=={{header|Rust}}==
<syntaxhighlight lang="text">#![feature(iterator_step_by)]
 
extern crate primal;
Line 3,372 ⟶ 4,293:
println!("Emirps-s between 7700 and 8000 : {:?}", vec2);
println!("10.000-th emirp : {}", emirp_10_000);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,387 ⟶ 4,308:
===Using BigInt's isProbablePrime()===
The isProbablePrime() method performs a Miller-Rabin primality test to within a given certainty.
<langsyntaxhighlight lang="scala">def isEmirp( v:Long ) : Boolean = {
val b = BigInt(v.toLong)
val r = BigInt(v.toString.reverse.toLong)
Line 3,399 ⟶ 4,320:
println( "%32s".format( "Emirps between %d and %d: ".format( b1, b2 )) + {for( i <- b1 to b2 if( isEmirp(i) ) ) yield i}.mkString(",") )
println( "%32s".format( "%,d emirp: ".format( c )) + Iterator.from(2).filter( isEmirp(_) ).drop(c-1).next )
}</langsyntaxhighlight>
{{out}}
<pre> First 20 emirps: 13,17,31,37,71,73,79,97,107,113,149,157,167,179,199,311,337,347,359,389
Emirps between 7700 and 8000: 7717,7757,7817,7841,7867,7879,7901,7927,7949,7951,7963
10,000 emirp: 948349</pre>
=={{header|Scheme}}==
{{works with|Chez Scheme}}
<syntaxhighlight lang="scheme">; Primality test by simple trial division.
(define prime?
(lambda (num)
(if (< num 2)
#f
(let loop ((div 2))
(cond ((> (* div div) num) #t)
((zero? (modulo num div)) #f)
(else (loop (1+ div))))))))
 
; Check if number is an emirp prime.
(define emirp?
(lambda (num)
(and (prime? num)
(let ((rev (string->number (list->string (reverse (string->list (number->string num)))))))
(and (not (= num rev)) (prime? rev))))))
 
(printf "The first 20 emirps:")
(do ((num 1 (1+ num)) (cnt 0))
((>= cnt 20))
(when (emirp? num)
(set! cnt (1+ cnt))
(printf " ~d" num)))
(newline)
 
(printf "All emirps between 7700 and 8000:")
(do ((num 7700 (1+ num)))
((>= num 8000))
(when (emirp? num)
(printf " ~d" num)))
(newline)
 
(printf "The 10000th emirp: ~d~%"
(do ((num 1 (1+ num)) (cnt 0))
((>= cnt 10000) (1- num))
(when (emirp? num) (set! cnt (1+ cnt)))))</syntaxhighlight>
{{out}}
<pre>The first 20 emirps: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
All emirps between 7700 and 8000: 7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
The 10000th emirp: 948349</pre>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func forprimes(a, b, callback) {
for (var p = a.dec.next_prime; p <= b; p.next_prime!) {
callback(p)
Line 3,437 ⟶ 4,400:
forprimes(7700, 8000, {|p| is_emirp(p) && take(p) })
}.join(' '))
say ("The 10,000'th emirp: ", emirp_list(10000)[-1])</langsyntaxhighlight>
{{out}}
<pre>
Line 3,444 ⟶ 4,407:
The 10,000'th emirp: 948349
</pre>
 
=={{header|Smalltalk}}==
Works with Smalltalk/X
Line 3,451 ⟶ 4,415:
 
First an emirp checker:
<langsyntaxhighlight lang="smalltalk">isEmirp :=
[:p | |e|
(e := p asString reversed asNumber) isPrime
and:[ e ~= p ]
].</langsyntaxhighlight>
 
an infinite list of primes:
<langsyntaxhighlight lang="smalltalk">primeGen :=
[:n |
LazyCons car:n cdr:[primeGen value:(n nextPrime)]
].</langsyntaxhighlight>
 
an infinite list of emirps, taking an infinite list of primes as arg:
<langsyntaxhighlight lang="smalltalk">emirpGen :=
[:l | |rest el|
rest := l.
[ el := rest car. rest := rest cdr. isEmirp value:el ] whileFalse.
LazyCons car:el cdr:[emirpGen value:rest]
].</langsyntaxhighlight>
two infinite lists:
<langsyntaxhighlight lang="smalltalk">listOfPrimes := primeGen value:2.
listOfEmirps := emirpGen value:listOfPrimes.</langsyntaxhighlight>
generating output:
<langsyntaxhighlight lang="smalltalk">Transcript
show:'first 20 emirps: ';
showCR:(listOfEmirps take:20) asArray.
Line 3,484 ⟶ 4,448:
Transcript
show:'10000''th emirp: ';
showCR:(listOfEmirps nth:10000).</langsyntaxhighlight>
 
Generates:<pre>
Line 3,492 ⟶ 4,456:
 
LazyCons is easily defined as:
<syntaxhighlight lang ="smalltalk">Object subclass: #Cons instancevariableNames:'car cdr'.
instancevariableNames:'car cdr'.
 
car:newCar cdr:newCdr
car := newCar. cdr := newCdr
Line 3,507 ⟶ 4,473:
cdr := cdr value.
self changeClassTo:Cons.
^cdr</langsyntaxhighlight>
 
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">emirp 1000
list in 1/20, noobs noh
 
Line 3,564 ⟶ 4,530:
+--------+
| 948349 |
+--------+</langsyntaxhighlight>
 
Now the definition of ''emirp.ado'':
 
<langsyntaxhighlight lang="stata">program emirp
args n
qui clear
Line 3,600 ⟶ 4,566:
st_store(.,1,a)
}
end</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">import Foundation
 
extension BinaryInteger {
var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
 
let max = Self(ceil((Double(self).squareRoot())))
 
for i in stride(from: 2, through: max, by: 1) where self % i == 0 {
return false
}
 
return true
}
}
 
func isEmirp<T: BinaryInteger>(n: T) -> Bool {
guard n.isPrime else {
return false
}
 
var aux = n
var revPrime = T(0)
 
while aux > 0 {
revPrime = revPrime * 10 + aux % 10
aux /= 10
}
 
guard n != revPrime else {
return false
}
 
return revPrime.isPrime
}
 
let lots = (2...).lazy.filter(isEmirp).prefix(10000)
let rang = (7700...8000).filter(isEmirp)
 
print("First 20 emirps: \(Array(lots.prefix(20)))")
print("Emirps between 7700 and 8000: \(rang)")
print("10,000th emirp: \(Array(lots).last!)")</syntaxhighlight>
 
{{out}}
 
<pre>First 20 emirps: [13, 17, 31, 37, 71, 73, 79, 97, 107, 113, 149, 157, 167, 179, 199, 311, 337, 347, 359, 389]
Emirps between 7700 and 8000: [7717, 7757, 7817, 7841, 7867, 7879, 7901, 7927, 7949, 7951, 7963]
10,000th emirp: 948349</pre>
 
=={{header|Tcl}}==
{{tcllib|math::numtheory}}
<langsyntaxhighlight lang="tcl">package require math::numtheory
 
# Import only to keep line lengths down
Line 3,627 ⟶ 4,648:
if {[emirp? $n] && [incr ne] == 10000} break
}
puts "10,000: $n"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,634 ⟶ 4,655:
10,000: 948349
</pre>
 
 
=={{header|VBA}}==
 
<langsyntaxhighlight lang="vb">Option Explicit
 
Private Const MAX As Long = 5000000
Line 3,751 ⟶ 4,771:
On Error GoTo 0
End If
End Function</langsyntaxhighlight>
{{out}}
<pre>At this point : Execution time = 13,23047 seconds.
Line 3,759 ⟶ 4,779:
all emirps between 7,700 and 8,000: 7717, 7757, 7817, 7841, 7867, 7879, 7901, 7927, 7949, 7951, 7963
the 10,000th emirp: 948349</pre>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Imports System.Runtime.CompilerServices
 
Module Module1
<Extension()>
Function ToHashSet(Of T)(source As IEnumerable(Of T)) As HashSet(Of T)
Return New HashSet(Of T)(source)
End Function
 
<Extension()>
Function Reverse(number As Integer) As Integer
If number < 0 Then
Return -Reverse(-number)
End If
If number < 10 Then
Return number
End If
 
Dim rev = 0
While number > 0
rev = rev * 10 + number Mod 10
number = number \ 10
End While
 
Return rev
End Function
 
<Extension()>
Function Delimit(Of T)(source As IEnumerable(Of T), Optional seperator As String = " ") As String
Return String.Join(If(seperator, " "), source)
End Function
 
Iterator Function Primes(bound As Integer) As IEnumerable(Of Integer)
If bound < 2 Then
Return
End If
Yield 2
 
Dim composite As New BitArray((bound - 1) / 2)
Dim limit As Integer = Int((Int(Math.Sqrt(bound)) - 1) / 2)
For i = 0 To limit - 1
If composite(i) Then
Continue For
End If
Dim prime = 2 * i + 3
Yield prime
 
For j As Integer = Int((prime * prime - 2) / 2) To composite.Count - 1 Step prime
composite(j) = True
Next
Next
For i = limit To composite.Count - 1
If Not composite(i) Then
Yield 2 * i + 3
End If
Next
End Function
 
Iterator Function FindEmirpPrimes(limit As Integer) As IEnumerable(Of Integer)
Dim ps = Primes(limit).ToHashSet()
 
For Each p In ps
Dim rev = p.Reverse()
If rev <> p AndAlso ps.Contains(rev) Then
Yield p
End If
Next
End Function
 
Sub Main()
Dim limit = 1_000_000
Console.WriteLine("First 20:")
Console.WriteLine(FindEmirpPrimes(limit).Take(20).Delimit())
Console.WriteLine()
 
Console.WriteLine("Between 7700 and 8000:")
Console.WriteLine(FindEmirpPrimes(limit).SkipWhile(Function(p) p < 7700).TakeWhile(Function(p) p < 8000).Delimit())
Console.WriteLine()
 
Console.WriteLine("10000th:")
Console.WriteLine(FindEmirpPrimes(limit).ElementAt(9999))
End Sub
 
End Module</syntaxhighlight>
{{out}}
<pre>First 20:
13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
 
Between 7700 and 8000:
7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
 
10000th:
948349</pre>
 
=={{header|Wren}}==
{{libheader|Wren-math}}
<syntaxhighlight lang="wren">import "./math" for Int
 
var isEmirp = Fn.new{ |n|
if (!Int.isPrime(n)) return false
var ns = "%(n)"
var rs = ns[-1..0]
var r = Num.fromString(rs)
if (r == n) return false
if (Int.isPrime(r)) return true
return false
}
 
System.print("The first 20 emirps are:")
var count = 0
var i = 3
while (count < 20) {
if (isEmirp.call(i)) {
count = count + 1
System.write("%(i) ")
}
i = i + 2
}
 
System.print("\n\nThe emirps between 7700 and 8000 are:")
i = 7701
while (i < 8000) {
if (isEmirp.call(i)) System.write("%(i) ")
i = i + 2
}
 
System.write("\n\nThe 10,000th emirp is ")
count = 0
i = 1
while (count < 10000) {
i = i + 2
if (isEmirp.call(i)) {
count = count + 1
}
}
System.print(i)</syntaxhighlight>
 
{{out}}
<pre>
The first 20 emirps are:
13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
 
The emirps between 7700 and 8000 are:
7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
 
The 10,000th emirp is 948349
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
 
func Reverse(N); \Return the value of N with its digits reversed
int N, M;
[M:= 0;
repeat N:= N/10;
M:= M*10 + rem(0);
until N = 0;
return M;
];
 
int N, M, Cnt;
[N:= 13; Cnt:= 0;
Text(0, "First 20 emirps:^m^j");
loop [if IsPrime(N) then
[M:= Reverse(N);
if IsPrime(M) and M # N then
[Cnt:= Cnt+1;
if Cnt <= 20 then
[IntOut(0, N); ChOut(0, ^ )];
if Cnt = 20 then
Text(0, "^m^jEmirps between 7700 and 8000:^m^j");
if N >= 7700 and N <= 8000 then
[IntOut(0, N); ChOut(0, ^ )];
if Cnt = 10_000 then
[Text(0, "^m^jThe 10,000 emirp: ");
IntOut(0, N);
CrLf(0);
quit;
];
];
];
N:= N+2;
];
]</syntaxhighlight>
{{out}}
<pre>
First 20 emirps:
13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389
Emirps between 7700 and 8000:
7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963
The 10,000 emirp: 948349
</pre>
 
=={{header|zkl}}==
Uses the solution from task [[Extensible prime generator#zkl]]. Saves the primes to a list, which gets pretty big.
<langsyntaxhighlight lang="zkl">var PS=Import("Src/ZenKinetic/sieve").postponed_sieve;
var ps=Utils.Generator(PS), plist=ps.walk(10).copy();
 
Line 3,776 ⟶ 4,999:
Utils.Generator(PS).filter(fcn(p){if(p>8000)return(Void.Stop); p>7700 and isEmirp(p)});
 
Utils.Generator(PS).reduce(fcn(N,p){N+=isEmirp(p); (N==10000) and T(Void.Stop,p) or N },0);</langsyntaxhighlight>
{{out}}
<pre>
1,983

edits