Nice primes: Difference between revisions

From Rosetta Code
Content added Content deleted
(Task in PHP)
(22 intermediate revisions by 14 users not shown)
Line 27: Line 27:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>F is_prime(a)
<syntaxhighlight lang="11l">F is_prime(a)
I a == 2
I a == 2
R 1B
R 1B
Line 42: Line 42:
L(n) 501..999
L(n) 501..999
I is_prime(digital_root(n)) & is_prime(n)
I is_prime(digital_root(n)) & is_prime(n)
print(n, end' ‘ ’)</lang>
print(n, end' ‘ ’)</syntaxhighlight>


{{out}}
{{out}}
Line 51: Line 51:
=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Sieve of Eratosthenes}}
{{libheader|Action! Sieve of Eratosthenes}}
<lang Action!>INCLUDE "H6:SIEVE.ACT"
<syntaxhighlight lang="action!">INCLUDE "H6:SIEVE.ACT"


BYTE Func IsNicePrime(INT i BYTE ARRAY primes)
BYTE Func IsNicePrime(INT i BYTE ARRAY primes)
Line 90: Line 90:
OD
OD
PrintF("%E%EThere are %I nice primes",count)
PrintF("%E%EThere are %I nice primes",count)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Nice_primes.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Nice_primes.png Screenshot from Atari 8-bit computer]
Line 101: Line 101:
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{libheader|ALGOL 68-primes}}
{{libheader|ALGOL 68-primes}}
<lang algol68>BEGIN # find nice primes - primes whose digital root is also prime #
<syntaxhighlight lang="algol68">BEGIN # find nice primes - primes whose digital root is also prime #
INT min prime = 501;
INT min prime = 501;
INT max prime = 999;
INT max prime = 999;
Line 131: Line 131:
FI
FI
OD
OD
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 140: Line 140:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin % find some nice primes - primes whose digital root is prime %
<syntaxhighlight lang="algolw">begin % find some nice primes - primes whose digital root is prime %
% returns the digital root of n in base 10 %
% returns the digital root of n in base 10 %
integer procedure digitalRoot( integer value n ) ;
integer procedure digitalRoot( integer value n ) ;
Line 183: Line 183:
end
end
end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 224: Line 224:
=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<lang APL>(⊢(/⍨)(∧/(2=(0+.=⍳|⊢))¨∘(⊢,(+/10⊥⍣¯1⊢)⍣(9≥⊣)))¨) 500+⍳500</lang>
<syntaxhighlight lang="apl">(⊢(/⍨)(∧/(2=(0+.=⍳|⊢))¨∘(⊢,(+/10⊥⍣¯1⊢)⍣(9≥⊣)))¨) 500+⍳500</syntaxhighlight>
{{out}}
{{out}}
<pre>509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947
<pre>509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947
Line 231: Line 231:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
sumn formula borrowed from the [https://www.rosettacode.org/wiki/Nice_primes#Factor Factor] solution.
sumn formula borrowed from the [https://www.rosettacode.org/wiki/Nice_primes#Factor Factor] solution.
<lang applescript>on sieveOfEratosthenes(limit)
<syntaxhighlight lang="applescript">on sieveOfEratosthenes(limit)
script o
script o
property numberList : {missing value}
property numberList : {missing value}
Line 272: Line 272:
end nicePrimes
end nicePrimes


return nicePrimes(501, 999)</lang>
return nicePrimes(501, 999)</syntaxhighlight>
{{output}}
{{output}}
<lang applescript>{509, 547, 563, 569, 587, 599, 601, 617, 619, 641, 653, 659, 673, 677, 691, 709, 727, 743, 761, 797, 821, 839, 853, 857, 887, 907, 911, 929, 941, 947, 977, 983, 997}</lang>
<syntaxhighlight lang="applescript">{509, 547, 563, 569, 587, 599, 601, 617, 619, 641, 653, 659, 673, 677, 691, 709, 727, 743, 761, 797, 821, 839, 853, 857, 887, 907, 911, 929, 941, 947, 977, 983, 997}</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">sumd: function [n][

<lang rebol>sumd: function [n][
s: sum digits n
s: sum digits n
(1 = size digits s)? -> return s
(1 = size digits s)? -> return s
Line 288: Line 287:


loop split.every:10 select 500..1000 => nice? 'a ->
loop split.every:10 select 500..1000 => nice? 'a ->
print map a => [pad to :string & 4]</lang>
print map a => [pad to :string & 4]</syntaxhighlight>


{{out}}
{{out}}
Line 298: Line 297:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f NICE_PRIMES.AWK
# syntax: GAWK -f NICE_PRIMES.AWK
BEGIN {
BEGIN {
Line 337: Line 336:
return(sum)
return(sum)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 377: Line 376:


=={{header|BASIC}}==
=={{header|BASIC}}==
<lang basic>10 DEFINT A-Z: B=500: E=1000
<syntaxhighlight lang="basic">10 DEFINT A-Z: B=500: E=1000
20 DIM P(E): P(0)=-1: P(1)=-1
20 DIM P(E): P(0)=-1: P(1)=-1
30 FOR I=2 TO SQR(E)
30 FOR I=2 TO SQR(E)
Line 387: Line 386:
90 IF J>0 THEN S=S+J MOD 10: J=J\10: GOTO 90
90 IF J>0 THEN S=S+J MOD 10: J=J\10: GOTO 90
100 IF S>9 THEN J=S: GOTO 80 ELSE IF NOT P(S) THEN PRINT I,
100 IF S>9 THEN J=S: GOTO 80 ELSE IF NOT P(S) THEN PRINT I,
110 NEXT</lang>
110 NEXT</syntaxhighlight>
{{out}}
{{out}}
<pre> 509 547 563 569 587
<pre> 509 547 563 569 587
Line 398: Line 397:


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"
manifest $(
manifest $(
begin = 500
begin = 500
Line 434: Line 433:
writef("%N*N", i)
writef("%N*N", i)
freevec(prime)
freevec(prime)
$)</lang>
$)</syntaxhighlight>


{{out}}
{{out}}
Line 470: Line 469:
983
983
997</pre>
997</pre>



=={{header|C}}==
=={{header|C}}==
{{trans|C++}}
{{trans|C++}}
<lang c>#include <stdbool.h>
<syntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
#include <stdio.h>


Line 523: Line 523:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Nice primes between 500 and 1000:
<pre>Nice primes between 500 and 1000:
Line 533: Line 533:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


bool is_prime(unsigned int n) {
bool is_prime(unsigned int n) {
Line 567: Line 567:
}
}
std::cout << '\n' << count << " nice primes found.\n";
std::cout << '\n' << count << " nice primes found.\n";
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 581: Line 581:
=={{header|D}}==
=={{header|D}}==
{{trans|C++}}
{{trans|C++}}
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


bool isPrime(uint n) {
bool isPrime(uint n) {
Line 627: Line 627:
writeln;
writeln;
writeln(count, " nice primes found.");
writeln(count, " nice primes found.");
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Nice primes between 500 and 1000:
<pre>Nice primes between 500 and 1000:
Line 635: Line 635:
977 983 997
977 983 997
33 nice primes found.</pre>
33 nice primes found.</pre>


=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}


<syntaxhighlight lang="Delphi">

function IsPrime(N: int64): boolean;
{Fast, optimised prime test}
var I,Stop: int64;
begin
if (N = 2) or (N=3) then Result:=true
else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false
else
begin
I:=5;
Stop:=Trunc(sqrt(N+0.0));
Result:=False;
while I<=Stop do
begin
if ((N mod I) = 0) or ((N mod (I + 2)) = 0) then exit;
Inc(I,6);
end;
Result:=True;
end;
end;



function SumDigits(N: integer): integer;
{Sum the integers in a number}
var T: integer;
begin
Result:=0;
repeat
begin
T:=N mod 10;
N:=N div 10;
Result:=Result+T;
end
until N<1;
end;



function IsNiceNumber(N: integer): boolean;
{Return True if N is a nice number}
var Sum: integer;
begin
Result:=False;
{N must be primes}
if not IsPrime(N) then exit;
{Keep summing until one digit number}
Sum:=N;
repeat Sum:=SumDigits(Sum)
until Sum<10;
{Must be prime too}
Result:=IsPrime(Sum);
end;


procedure ShowNicePrimes(Memo: TMemo);
{Display Nice Primes between 501 and 999}
var I,Cnt: integer;
var S: string;
begin
Cnt:=0; S:='';
for I:=501 to 999 do
if IsNiceNumber(I) then
begin
S:=S+Format('%4d',[i]);
Inc(Cnt);
if (Cnt mod 5)=0 then S:=S+#$0D#$0A;
end;
Memo.Lines.Add(Format('Nice Primes: %3D',[Cnt]));
Memo.Lines.Add(S);
end;

</syntaxhighlight>
{{out}}
<pre>
Nice Primes: 33
509 547 563 569 587
599 601 617 619 641
653 659 673 677 691
709 727 743 761 797
821 839 853 857 887
907 911 929 941 947
977 983 997

</pre>



=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)]
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)]
<lang fsharp>
<syntaxhighlight lang="fsharp">
// Nice primes. Nigel Galloway: March 22nd., 2021
// Nice primes. Nigel Galloway: March 22nd., 2021
let fN g=1+((g-1)%9) in primes32()|>Seq.skipWhile((>)500)|>Seq.takeWhile((>)1000)|>Seq.filter(fN>>isPrime)|>Seq.iter(printf "%d "); printfn ""
let fN g=1+((g-1)%9) in primes32()|>Seq.skipWhile((>)500)|>Seq.takeWhile((>)1000)|>Seq.filter(fN>>isPrime)|>Seq.iter(printf "%d "); printfn ""
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 658: Line 752:
({{math|<var>n</var> &#61; 0}} may not need to be special-cased depending on the behavior of your language's modulo operator.)
({{math|<var>n</var> &#61; 0}} may not need to be special-cased depending on the behavior of your language's modulo operator.)


<lang factor>USING: math math.primes prettyprint sequences ;
<syntaxhighlight lang="factor">USING: math math.primes prettyprint sequences ;


: digital-root ( m -- n ) 1 - 9 mod 1 + ;
: digital-root ( m -- n ) 1 - 9 mod 1 + ;


500 1000 primes-between [ digital-root prime? ] filter .</lang>
500 1000 primes-between [ digital-root prime? ] filter .</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:10em">
<pre style="height:10em">
Line 704: Line 798:
{{trans|Factor}}
{{trans|Factor}}
{{works with|Gforth}}
{{works with|Gforth}}
<lang forth>: prime? ( n -- ? ) here + c@ 0= ;
<syntaxhighlight lang="forth">: prime? ( n -- ? ) here + c@ 0= ;
: notprime! ( n -- ) here + 1 swap c! ;
: notprime! ( n -- ) here + 1 swap c! ;


Line 741: Line 835:


1000 500 print_nice_primes
1000 500 print_nice_primes
bye</lang>
bye</syntaxhighlight>


{{out}}
{{out}}
Line 752: Line 846:
33 nice primes found.
33 nice primes found.
</pre>
</pre>



=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>
<syntaxhighlight lang="freebasic">
Function isPrime(Byval ValorEval As Integer) As Boolean
Function isPrime(Byval ValorEval As Integer) As Boolean
If ValorEval <= 1 Then Return False
If ValorEval <= 1 Then Return False
Line 788: Line 881:
Print !"\n\n"; column; " buenos n£meros encontrados."
Print !"\n\n"; column; " buenos n£meros encontrados."
Sleep
Sleep
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 804: Line 897:
=={{header|Fōrmulæ}}==
=={{header|Fōrmulæ}}==


{{FormulaeEntry|page=https://formulae.org/?script=examples/Nice_primes}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.


'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.


[[File:Fōrmulæ - Nice primes 01.png]]
In '''[https://formulae.org/?example=Nice_primes this]''' page you can see the program(s) related to this task and their results.

'''Test case'''

[[File:Fōrmulæ - Nice primes 02.png]]

[[File:Fōrmulæ - Nice primes 03.png]]

'''Showing nice primes in the range 500 .. 1,000'''

[[File:Fōrmulæ - Nice primes 04.png]]

[[File:Fōrmulæ - Nice primes 05.png]]

[[File:Fōrmulæ - Nice primes 06.png]]


=={{header|Go}}==
=={{header|Go}}==
{{trans|Wren}}
{{trans|Wren}}
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 864: Line 971:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 871: Line 978:
</pre>
</pre>


=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
import Data.Char ( digitToInt )

isPrime :: Int -> Bool
isPrime n
|n == 2 = True
|n == 1 = False
|otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root]
where
root :: Int
root = floor $ sqrt $ fromIntegral n

digitsum :: Int -> Int
digitsum n = sum $ map digitToInt $ show n

findSumn :: Int -> Int
findSumn n = until ( (== 1) . length . show ) digitsum n

isNicePrime :: Int -> Bool
isNicePrime n = isPrime n && isPrime ( findSumn n )

solution :: [Int]
solution = filter isNicePrime [501..999]</syntaxhighlight>
{{out}}
<pre>
[509,547,563,569,587,599,601,617,619,641,653,659,673,677,691,709,727,743,761,797,821,839,853,857,887,907,911,929,941,947,977,983,997]
</pre>


=={{header|J}}==
=={{header|J}}==
Line 890: Line 1,025:
=={{header|Java}}==
=={{header|Java}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang java>public class NicePrimes {
<syntaxhighlight lang="java">public class NicePrimes {
private static boolean isPrime(long n) {
private static boolean isPrime(long n) {
if (n < 2) {
if (n < 2) {
Line 946: Line 1,081:
System.out.printf("%d nice primes found.%n", count);
System.out.printf("%d nice primes found.%n", count);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Nice primes between 500 and 1000
<pre>Nice primes between 500 and 1000
Line 961: Line 1,096:
This entry uses `is_prime` as defined at
This entry uses `is_prime` as defined at
[[Erd%C5%91s-primes#jq]].
[[Erd%C5%91s-primes#jq]].
<lang jq>def is_nice:
<syntaxhighlight lang="jq">def is_nice:
# input: a non-negative integer
# input: a non-negative integer
def sumn:
def sumn:
Line 973: Line 1,108:


# The task:
# The task:
range(501; 1000) | select(is_nice)</lang>
range(501; 1000) | select(is_nice)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,010: Line 1,145:
997
997
</pre>
</pre>

=={{header|Julia}}==
=={{header|Julia}}==
See [[Strange_numbers#Julia]] for the filter_open_interval function.
See [[Strange_numbers#Julia]] for the filter_open_interval function.
<lang julia>using Primes
<syntaxhighlight lang="julia">using Primes


isnice(n, base=10) = isprime(n) && (mod1(n - 1, base - 1) + 1) in [2, 3, 5, 7, 11, 13, 17, 19]
isnice(n, base=10) = isprime(n) && (mod1(n - 1, base - 1) + 1) in [2, 3, 5, 7, 11, 13, 17, 19]


filter_open_interval(500, 1000, isnice)
filter_open_interval(500, 1000, isnice)
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
Finding numbers matching isnice for open interval (500, 1000):
Finding numbers matching isnice for open interval (500, 1000):
Line 1,029: Line 1,165:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|C}}
{{trans|C}}
<lang scala>fun isPrime(n: Long): Boolean {
<syntaxhighlight lang="scala">fun isPrime(n: Long): Boolean {
if (n < 2) {
if (n < 2) {
return false
return false
Line 1,083: Line 1,219:
println()
println()
println("$count nice primes found.")
println("$count nice primes found.")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Nice primes between 500 and 1000:
<pre>Nice primes between 500 and 1000:
Line 1,094: Line 1,230:
=={{header|Lua}}==
=={{header|Lua}}==
{{trans|C}}
{{trans|C}}
<lang lua>function isPrime(n)
<syntaxhighlight lang="lua">function isPrime(n)
if n < 2 then
if n < 2 then
return false
return false
Line 1,144: Line 1,280:
n = n + 1
n = n + 1
end
end
print(count .. " nice primes found.")</lang>
print(count .. " nice primes found.")</syntaxhighlight>
{{out}}
{{out}}
<pre>Nice primes between 500 and 1000
<pre>Nice primes between 500 and 1000
Line 1,153: Line 1,289:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>ClearAll[summ]
<syntaxhighlight lang="mathematica">ClearAll[summ]
summ[n_] := FixedPoint[IntegerDigits /* Total, n]
summ[n_] := FixedPoint[IntegerDigits /* Total, n]
Select[Range[501, 999], PrimeQ[#] \[And] PrimeQ[summ[#]] &]</lang>
Select[Range[501, 999], PrimeQ[#] \[And] PrimeQ[summ[#]] &]</syntaxhighlight>
{{out}}
{{out}}
<pre>{509, 547, 563, 569, 587, 599, 601, 617, 619, 641, 653, 659, 673, 677, 691, 709, 727, 743, 761, 797, 821, 839, 853, 857, 887, 907, 911, 929, 941, 947, 977, 983, 997}</pre>
<pre>{509, 547, 563, 569, 587, 599, 601, 617, 619, 641, 653, 659, 673, 677, 691, 709, 727, 743, 761, 797, 821, 839, 853, 857, 887, 907, 911, 929, 941, 947, 977, 983, 997}</pre>

=={{header|PARI/GP}}==
<lang PARI/GP>nicePrimes( s, e ) = { local( m );
forprime( p = s, e,
m = p; \\
while( m > 9, \\ m == p mod 9
m = sumdigits( m ) ); \\
if( isprime( m ),
print1( i, " " ) ) );
}</lang>
or
<lang PARI/GP>apply( s -> s, select( s -> isprime( s % 9 ), primes( [500, 1000] )))</lang>


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import strutils, sugar
<syntaxhighlight lang="nim">import strutils, sugar


func isPrime(n: Positive): bool =
func isPrime(n: Positive): bool =
Line 1,202: Line 1,326:
for i, n in list:
for i, n in list:
stdout.write n, if (i + 1) mod 10 == 0: '\n' else: ' '
stdout.write n, if (i + 1) mod 10 == 0: '\n' else: ' '
echo()</lang>
echo()</syntaxhighlight>


{{out}}
{{out}}
Line 1,210: Line 1,334:
821 839 853 857 887 907 911 929 941 947
821 839 853 857 887 907 911 929 941 947
977 983 997 </pre>
977 983 997 </pre>

=={{header|OCaml}}==
After ruling out all multiples of three, <code>mod 9</code> (the digital root) can only return {1, 2, 4, 5, 7, 8}. Adding 6 before calculating <code>mod 9</code> makes all primes in the result even (and the composites odd), so <code>(n + 6) mod 9 land 1 = 0</code> is sufficient for checking the digital root.
<syntaxhighlight lang="ocaml">let is_nice_prime n =
let rec test x =
x * x > n || n mod x <> 0 && n mod (x + 2) <> 0 && test (x + 6)
in
if n < 5
then n lor 1 = 3
else n land 1 <> 0 && n mod 3 <> 0 && (n + 6) mod 9 land 1 = 0 && test 5

let () =
Seq.(ints 500 |> take 500 |> filter is_nice_prime |> iter (Printf.printf " %u"))
|> print_newline</syntaxhighlight>
{{out}}
<pre> 509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997</pre>

=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">/* REXX */
n=1000
prime = .Array~new(n)~fill(.true)~~remove(1)
p.=0
Do i = 2 to n
If prime[i] = .true Then Do
Do j = i * i to n by i
prime~remove(j)
End
p.i=1
End
End
z=0
ol=''
Do i=500 To 1000
If p.i then Do
dr=digroot(i)
If p.dr Then Do
ol=ol' 'i'('dr')'
z=z+1
If z//10=0 Then Do
Say strip(ol)
ol=''
End
End
End
End
Say strip(ol)
Say z 'nice primes in the range 500 to 1000'
Exit

digroot:
Parse Arg s
Do Until length(s)=1
dr=0
Do j=1 To length(s)
dr=dr+substr(s,j,1)
End
s=dr
End
Return s</syntaxhighlight>
{{out}}
<pre>509(5) 547(7) 563(5) 569(2) 587(2) 599(5) 601(7) 617(5) 619(7) 641(2)
653(5) 659(2) 673(7) 677(2) 691(7) 709(7) 727(7) 743(5) 761(5) 797(5)
821(2) 839(2) 853(7) 857(2) 887(5) 907(7) 911(2) 929(2) 941(5) 947(2)
977(5) 983(2) 997(7)
33 nice primes in the range 500 to 1000</pre>

=={{header|PARI/GP}}==
<syntaxhighlight lang="python">nicePrimes( s, e ) = { local( m );
forprime( p = s, e,
m = p; \\
while( m > 9, \\ m == p mod 9
m = sumdigits( m ) ); \\
if( isprime( m ),
print1( p, " " ) ) );
}</syntaxhighlight>
or
<syntaxhighlight lang="pari/gp">select( p -> isprime( p % 9 ), primes( [500, 1000] ))</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
{{libheader|ntheory}}
{{libheader|ntheory}}
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;


Line 1,230: Line 1,431:
$cnt = @nice_primes;
$cnt = @nice_primes;
print "Nice primes between $low and $high (total of $cnt):\n" .
print "Nice primes between $low and $high (total of $cnt):\n" .
(sprintf "@{['%5d' x $cnt]}", @nice_primes[0..$cnt-1]) =~ s/(.{55})/$1\n/gr;</lang>
(sprintf "@{['%5d' x $cnt]}", @nice_primes[0..$cnt-1]) =~ s/(.{55})/$1\n/gr;</syntaxhighlight>
{{out}}
{{out}}
<pre>Nice primes between 500 and 1000 (total of 33):
<pre>Nice primes between 500 and 1000 (total of 33):
Line 1,239: Line 1,440:
=={{header|Phix}}==
=={{header|Phix}}==
{{trans|Factor}}
{{trans|Factor}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">pdr</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;">return</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;">and</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</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;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">pdr</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;">return</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;">and</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</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;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">500</span><span style="color: #0000FF;">),</span><span style="color: #000000;">pdr</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">500</span><span style="color: #0000FF;">),</span><span style="color: #000000;">pdr</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;">"%d nice primes found:\n %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">join_by</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">11</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\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;">"%d nice primes found:\n %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">join_by</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">11</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n "</span><span style="color: #0000FF;">)})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,250: Line 1,451:
659 673 677 691 709 727 743 761 797 821 839
659 673 677 691 709 727 743 761 797 821 839
853 857 887 907 911 929 941 947 977 983 997
853 857 887 907 911 929 941 947 977 983 997
</pre>

=={{header|PHP}}==
{{trans|Python}}
<syntaxhighlight lang="php">
<?php
// Function to check if a number is prime
function isPrime($n) {
if ($n <= 1) {
return false;
}
for ($i = 2; $i <= sqrt($n); $i++) {
if ($n % $i == 0) {
return false;
}
}
return true;
}

// Function to sum the digits of a number until the sum is a single digit
function sumOfDigits($n) {
while ($n > 9) {
$sum = 0;
while ($n > 0) {
$sum += $n % 10;
$n = (int)($n / 10);
}
$n = $sum;
}
return $n;
}

function findNicePrimes($lower_limit=501, $upper_limit=1000) {
// Find all Nice primes within the specified range
$nice_primes = array();
for ($n = $lower_limit; $n < $upper_limit; $n++) {
if (isPrime($n)) {
$sumn = sumOfDigits($n);
if (isPrime($sumn)) {
array_push($nice_primes, $n);
}
}
}
return $nice_primes;
}
// Main loop to find and print "Nice Primes"
$nice_primes = findNicePrimes();
foreach ($nice_primes as $prime) {
echo $prime . " ";
}
?>
</syntaxhighlight>
{{out}}
<pre>
509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997
</pre>

=={{header|Python}}==
<syntaxhighlight lang="python">
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

def sum_of_digits(n):
"""Calculate the repeated sum of digits until the sum's length is 1."""
while n > 9:
n = sum(int(digit) for digit in str(n))
return n

def find_nice_primes(lower_limit=501, upper_limit=1000):
"""Find all Nice primes within the specified range."""
nice_primes = []
for n in range(lower_limit, upper_limit):
if is_prime(n):
sumn = sum_of_digits(n)
if is_prime(sumn):
nice_primes.append(n)
return nice_primes

# Example usage
nice_primes = find_nice_primes()
print(nice_primes)
</syntaxhighlight>
{{out}}
<pre>
[509, 547, 563, 569, 587, 599, 601, 617, 619, 641, 653, 659, 673, 677, 691, 709, 727, 743, 761, 797, 821, 839, 853, 857, 887, 907, 911, 929, 941, 947, 977, 983, 997]
</pre>
=={{header|PL/0}}==
<syntaxhighlight lang="pascal">
var n, sum, prime, i;
procedure sumdigitsofn;
var v, vover10;
begin
sum := 0;
v := n;
while v > 0 do begin
vover10 := v / 10;
sum := sum + ( v - ( vover10 * 10 ) );
v := vover10
end
end;
procedure isnprime;
var p;
begin
prime := 1;
if n < 2 then prime := 0;
if n > 2 then begin
prime := 0;
if odd( n ) then prime := 1;
p := 3;
while p * p <= n * prime do begin
if n - ( ( n / p ) * p ) = 0 then prime := 0;
p := p + 2;
end
end
end;
begin
i := 500;
while i < 999 do begin
i := i + 1;
n := i;
call isnprime;
if prime = 1 then begin
sum := n;
while sum > 9 do begin
call sumdigitsofn;
n := sum
end;
if sum = 2 then ! i;
if sum = 3 then ! i;
if sum = 5 then ! i;
if sum = 7 then ! i
end
end
end.
</syntaxhighlight>
{{out}}
Note: PL/0 can only output one value per line, to avoid a long output, the results have been manually combined to 7 per line.
<pre>
509 547 563 569 587 599 601
617 619 641 653 659 673 677
691 709 727 743 761 797 821
839 853 857 887 907 911 929
941 947 977 983 997
</pre>
</pre>


=={{header|PL/M}}==
=={{header|PL/M}}==
{{Trans|ALGOL 68}}
{{Trans|ALGOL 68}}
<lang plm>100H: /* FIND NICE PRIMES - PRIMES WHOSE DIGITAL ROOT IS ALSO PRIME */
<syntaxhighlight lang="plm">100H: /* FIND NICE PRIMES - PRIMES WHOSE DIGITAL ROOT IS ALSO PRIME */
BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
DECLARE FN BYTE, ARG ADDRESS;
DECLARE FN BYTE, ARG ADDRESS;
Line 1,333: Line 1,683:
END;
END;
END;
END;
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,339: Line 1,689:
673(7) 677(2) 691(7) 709(7) 727(7) 743(5) 761(5) 797(5) 821(2) 839(2) 853(7) 857(2)
673(7) 677(2) 691(7) 709(7) 727(7) 743(5) 761(5) 797(5) 821(2) 839(2) 853(7) 857(2)
887(5) 907(7) 911(2) 929(2) 941(5) 947(2) 977(5) 983(2) 997(7)
887(5) 907(7) 911(2) 929(2) 941(5) 947(2) 977(5) 983(2) 997(7)
</pre>

=={{header|Quackery}}==
<code>eratosthenes</code> and <code>isprime</code> are defined at [[Sieve of Eratosthenes#Quackery]].

<syntaxhighlight lang="quackery"> 1000 eratosthenes

[ 1 - 9 mod 1+ ] is digitalroot ( n --> n )

[ dup digitalroot isprime
swap isprime and ] is niceprime ( n --> b )

500 times
[ i^ 500 + niceprime if
[ i^ 500 + echo sp ] ]</syntaxhighlight>

{{out}}

<pre>509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997
</pre>
</pre>


=={{header|Raku}}==
=={{header|Raku}}==
<lang perl6>sub digroot ($r) { .tail given $r, { [+] .comb } ... { .chars == 1 } }
<syntaxhighlight lang="raku" line>sub digroot ($r) { .tail given $r, { [+] .comb } ... { .chars == 1 } }
my @is-nice = lazy (0..*).map: { .&is-prime && .&digroot.&is-prime ?? $_ !! False };
my @is-nice = lazy (0..*).map: { .&is-prime && .&digroot.&is-prime ?? $_ !! False };
say @is-nice[500 ^..^ 1000].grep(*.so).batch(11)».fmt("%4d").join: "\n";</lang>
say @is-nice[500 ^..^ 1000].grep(*.so).batch(11)».fmt("%4d").join: "\n";</syntaxhighlight>
{{out}}
{{out}}
<pre> 509 547 563 569 587 599 601 617 619 641 653
<pre> 509 547 563 569 587 599 601 617 619 641 653
Line 1,351: Line 1,720:


Alternately, with somewhat better separation of concerns.
Alternately, with somewhat better separation of concerns.
<lang perl6>sub digroot ($r) { ($r, { .comb.sum } … { .chars == 1 }).tail }
<syntaxhighlight lang="raku" line>sub digroot ($r) { ($r, { .comb.sum } … { .chars == 1 }).tail }
sub is-nice ($_) { .is-prime && .&digroot.is-prime }
sub is-nice ($_) { .is-prime && .&digroot.is-prime }
say (500 ^..^ 1000).grep( *.&is-nice ).batch(11)».fmt("%4d").join: "\n";</lang>
say (500 ^..^ 1000).grep( *.&is-nice ).batch(11)».fmt("%4d").join: "\n";</syntaxhighlight>
Same output.
Same output.


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program finds and displays nice primes, primes whose digital root is also prime.*/
<syntaxhighlight lang="rexx">/*REXX program finds and displays nice primes, primes whose digital root is also prime.*/
parse arg lo hi cols . /*obtain optional argument from the CL.*/
parse arg lo hi cols . /*obtain optional argument from the CL.*/
if lo=='' | lo=="," then lo= 500 /*Not specified? Then use the default.*/
if lo=='' | lo=="," then lo= 500 /*Not specified? Then use the default.*/
Line 1,401: Line 1,770:
end /*k*/ /* [↑] only process numbers ≤ √ J */
end /*k*/ /* [↑] only process numbers ≤ √ J */
#= #+1; @.#= j; s.#= j*j; !.j= 1 /*bump # of Ps; assign next P; P²; P# */
#= #+1; @.#= j; s.#= j*j; !.j= 1 /*bump # of Ps; assign next P; P²; P# */
end /*j*/; return</lang>
end /*j*/; return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 1,416: Line 1,785:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
load "stdlib.ring"
load "stdlib.ring"


Line 1,445: Line 1,814:


see "done..." + nl
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,484: Line 1,853:
33: 997 > Σ = 7
33: 997 > Σ = 7
done...
done...
</pre>

=={{header|RPL}}==
≪ { } 500
'''DO'''
NEXTPRIME
'''IF''' DUP 1 - 9 MOD 1 + ISPRIME? '''THEN'''
SWAP OVER + SWAP '''END'''
'''UNTIL''' DUP 1000 ≥ '''END'''
DROP
≫ '<span style="color:blue">TASK</span>' STO
{{out}}
<pre>
1: { 509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997 }
</pre>

=={{header|Ruby}}==
<syntaxhighlight lang="ruby">require 'prime'

class Integer
def dig_root = (1+(self-1).remainder(9))
def nice? = prime? && dig_root.prime?
end

p (500..1000).select(&:nice?)
</syntaxhighlight>
{{out}}
<pre>[509, 547, 563, 569, 587, 599, 601, 617, 619, 641, 653, 659, 673, 677, 691, 709, 727, 743, 761, 797, 821, 839, 853, 857, 887, 907, 911, 929, 941, 947, 977, 983, 997]
</pre>
</pre>


=={{header|Rust}}==
=={{header|Rust}}==
{{trans|Factor}}
{{trans|Factor}}
<lang rust>// [dependencies]
<syntaxhighlight lang="rust">// [dependencies]
// primal = "0.3"
// primal = "0.3"


Line 1,509: Line 1,906:
fn main() {
fn main() {
nice_primes(500, 1000);
nice_primes(500, 1000);
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,549: Line 1,946:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const func boolean: isPrime (in integer: number) is func
const func boolean: isPrime (in integer: number) is func
Line 1,578: Line 1,975:
end if;
end if;
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,585: Line 1,982:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func digital_root(n, base=10) {
<syntaxhighlight lang="ruby">func digital_root(n, base=10) {
while (n.len(base) > 1) {
while (n.len(base) > 1) {
n = n.sumdigits(base)
n = n.sumdigits(base)
Line 1,592: Line 1,989:
}
}


say primes(500, 1000).grep { digital_root(_).is_prime }</lang>
say primes(500, 1000).grep { digital_root(_).is_prime }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,600: Line 1,997:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-math}}
{{libheader|Wren-math}}
{{libheader|Wren-trait}}
{{libheader|Wren-iterate}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/math" for Int
<syntaxhighlight lang="wren">import "./math" for Int
import "/trait" for Stepped
import "./iterate" for Stepped
import "/fmt" for Fmt
import "./fmt" for Fmt


var sumDigits = Fn.new { |n|
var sumDigits = Fn.new { |n|
Line 1,626: Line 2,023:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,664: Line 2,061:
32: 983 -> Σ = 2
32: 983 -> Σ = 2
33: 997 -> Σ = 7
33: 997 -> Σ = 7
</pre>

=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func IntLen(N); \Return number of digits in N
int N, I;
for I:= 1 to 10 do
[N:= N/10;
if N = 0 then return I;
];

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 SumDigits(N); \Return sum of digits in N
int N, Sum;
[Sum:= 0;
repeat N:= N/10;
Sum:= Sum + rem(0);
until N=0;
return Sum;
];

int C, N, SumN;
[C:= 0;
for N:= 501 to 999 do
if IsPrime(N) then
[SumN:= N;
repeat SumN:= SumDigits(SumN);
until IntLen(SumN) = 1;
if IsPrime(SumN) then
[IntOut(0, N);
C:= C+1;
if rem (C/10) then ChOut(0, ^ ) else CrLf(0);
];
];
]</syntaxhighlight>

{{out}}
<pre>
509 547 563 569 587 599 601 617 619 641
653 659 673 677 691 709 727 743 761 797
821 839 853 857 887 907 911 929 941 947
977 983 997
</pre>
</pre>

Revision as of 14:52, 2 March 2024

Nice primes is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.


Task
  1.   Take an positive integer   n
  2.   sumn   is the sum of the decimal digits of   n
  3.   If  sumn's  length is greater than   1   (unity),   repeat step 2 for   n = sumn
  4.   Stop when  sumn's  length is equal to   1   (unity)


If   n   and   sumn   are prime,   then   n   is a   Nice prime

Let     500   <   n   <   1000


Example
       853 (prime)
       8 + 5 + 3 = 16
       1 + 6 = 7 (prime)


Also see



11l

F is_prime(a)
   I a == 2
      R 1B
   I a < 2 | a % 2 == 0
      R 0B
   L(i) (3 .. Int(sqrt(a))).step(2)
      I a % i == 0
         R 0B
   R 1B

F digital_root(n)
   R 1 + (n - 1) % 9

L(n) 501..999
   I is_prime(digital_root(n)) & is_prime(n)
      print(n, end' ‘ ’)
Output:
509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997 

Action!

INCLUDE "H6:SIEVE.ACT"

BYTE Func IsNicePrime(INT i BYTE ARRAY primes)
  BYTE sum,d

  IF primes(i)=0 THEN
    RETURN (0)
  FI

  DO
    sum=0
    WHILE i#0
    DO
      d=i MOD 10
      sum==+d
      i==/10
    OD
    IF sum<10 THEN
      EXIT
    FI
    i=sum
  OD
RETURN (primes(sum))

PROC Main()
  DEFINE MAX="999"
  BYTE ARRAY primes(MAX+1)
  INT i,count=[0]

  Put(125) PutE() ;clear the screen
  Sieve(primes,MAX+1)
  FOR i=501 TO 999
  DO
    IF IsNicePrime(i,primes) THEN
      PrintI(i) Put(32)
      count==+1
    FI
  OD
  PrintF("%E%EThere are %I nice primes",count)
RETURN
Output:

Screenshot from Atari 8-bit computer

509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997

There are 33 nice primes

ALGOL 68

BEGIN  # find nice primes - primes whose digital root is also prime #
    INT min prime = 501;
    INT max prime = 999;
    # sieve the primes to max prime #
    PR read "primes.incl.a68" PR
    []BOOL prime = PRIMESIEVE max prime;
    # find the nice primes #
    INT nice count := 0;
    FOR n FROM min prime TO max prime DO
        IF prime[ n ] THEN
            # have a prime #
            INT digit sum := 0;
            INT v         := n;
            WHILE digit sum := 0;
                  WHILE v > 0 DO
                      digit sum +:= v MOD 10;
                      v OVERAB 10
                  OD;
                  digit sum > 9
            DO
                v := digit sum
            OD;
            IF prime( digit sum ) THEN
                # the digital root is prime #
                nice count +:= 1;
                print( ( " ", whole( n, -3 ), "(", whole( digit sum, 0 ), ")" ) );
                IF nice count MOD 12 = 0 THEN print( ( newline ) ) FI
            FI
        FI
    OD
END
Output:
 509(5) 547(7) 563(5) 569(2) 587(2) 599(5) 601(7) 617(5) 619(7) 641(2) 653(5) 659(2)
 673(7) 677(2) 691(7) 709(7) 727(7) 743(5) 761(5) 797(5) 821(2) 839(2) 853(7) 857(2)
 887(5) 907(7) 911(2) 929(2) 941(5) 947(2) 977(5) 983(2) 997(7)

ALGOL W

begin % find some nice primes - primes whose digital root is prime           %
    % returns the digital root of n in base 10                               %
    integer procedure digitalRoot( integer value  n ) ;
        if n = 0 then 0
        else begin
            integer root;
            root := ( abs n ) rem 9;
            if root = 0 then 9 else root
        end digitalRoot ;
    % sets p( 1 :: n ) to a sieve of primes up to n %
    procedure Eratosthenes ( logical array p( * ) ; integer value n ) ;
    begin
        p( 1 ) := false; p( 2 ) := true;
        for i := 3 step 2 until n do p( i ) := true;
        for i := 4 step 2 until n do p( i ) := false;
        for i := 3 step 2 until truncate( sqrt( n ) ) do begin
            integer ii; ii := i + i;
            if p( i ) then for pr := i * i step ii until n do p( pr ) := false
        end for_i ;
    end Eratosthenes ;
    integer MIN_PRIME, MAX_PRIME;
    MIN_PRIME :=  501;
    MAX_PRIME :=  999;
    % find the nice primes in the exclusive range 500 < prime < 1000 %
    begin
        logical array p ( 1 :: MAX_PRIME );
        integer       nCount;
        % construct a sieve of primes up to the maximum required     %
        Eratosthenes( p, MAX_PRIME );
        % show the primes that are nice                              %
        write( i_w := 1, s_w := 0, "Nice primes from ", MIN_PRIME, " to ", MAX_PRIME );
        for i := MIN_PRIME until MAX_PRIME do begin
            if p( i ) then begin
                integer dr;
                dr := digitalRoot( i );
                if p( dr ) then begin
                    nCount := nCount + 1;
                    write( i_w := 3, s_w := 0, nCount, ":", i, "  dr(", i_w := 1, dr, ")" )
                end if_dr_p
            end if_p_i
        end for_i
    end
end.
Output:
Nice primes from 501 to 999
  1:509  dr(5)
  2:547  dr(7)
  3:563  dr(5)
  4:569  dr(2)
  5:587  dr(2)
  6:599  dr(5)
  7:601  dr(7)
  8:617  dr(5)
  9:619  dr(7)
 10:641  dr(2)
 11:653  dr(5)
 12:659  dr(2)
 13:673  dr(7)
 14:677  dr(2)
 15:691  dr(7)
 16:709  dr(7)
 17:727  dr(7)
 18:743  dr(5)
 19:761  dr(5)
 20:797  dr(5)
 21:821  dr(2)
 22:839  dr(2)
 23:853  dr(7)
 24:857  dr(2)
 25:887  dr(5)
 26:907  dr(7)
 27:911  dr(2)
 28:929  dr(2)
 29:941  dr(5)
 30:947  dr(2)
 31:977  dr(5)
 32:983  dr(2)
 33:997  dr(7)

APL

Works with: Dyalog APL
((/⍨)(/(2=(0+.=⍳|⊢))¨∘(⊢,(+/10¯1)(9≥⊣)))¨) 500+⍳500
Output:
509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947
      977 983 997

AppleScript

sumn formula borrowed from the Factor solution.

on sieveOfEratosthenes(limit)
    script o
        property numberList : {missing value}
    end script
    
    repeat with n from 2 to limit
        set end of o's numberList to n
    end repeat
    repeat with n from 2 to (limit ^ 0.5 div 1)
        if (item n of o's numberList is n) then
            repeat with multiple from (n * n) to limit by n
                set item multiple of o's numberList to missing value
            end repeat
        end if
    end repeat
    
    return o's numberList's numbers
end sieveOfEratosthenes

on nicePrimes(a, b)
    script o
        property primes : reverse of sieveOfEratosthenes(b)
        property niceOnes : {}
    end script
    
    repeat with n in o's primes
        set n to n's contents
        if (n < a) then exit repeat
        set sumn to (n - 1) mod 9 + 1
        -- n being a prime, sumn can obviously never be 0 here. Tests suggest that it's never 6 or 9
        -- either and that it's only ever 3 when n is 3. Occurrences of the other single-digit
        -- possibilities are fairly evenly distributed. Testing for a prime result — 2, 5, 7, or the
        -- very unlikely 3 — requires one to four tests, depending on which test eventually decides
        -- the matter. An alternative is to eliminate 8, 4, and 1 instead, which can be done with
        -- only one or two tests. The test eliminating both 8 and 4 should be tried first.
        if ((sumn mod 4 > 0) and (sumn > 1)) then set end of o's niceOnes to n
    end repeat
    
    return reverse of o's niceOnes
end nicePrimes

return nicePrimes(501, 999)
Output:
{509, 547, 563, 569, 587, 599, 601, 617, 619, 641, 653, 659, 673, 677, 691, 709, 727, 743, 761, 797, 821, 839, 853, 857, 887, 907, 911, 929, 941, 947, 977, 983, 997}

Arturo

sumd: function [n][
    s: sum digits n 
    (1 = size digits s)? -> return s
                         -> return sumd s
]

nice?: function [x] -> and? prime? x
                            prime? sumd x

loop split.every:10 select 500..1000 => nice? 'a ->
    print map a => [pad to :string & 4]
Output:
 509  547  563  569  587  599  601  617  619  641 
 653  659  673  677  691  709  727  743  761  797 
 821  839  853  857  887  907  911  929  941  947 
 977  983  997

AWK

# syntax: GAWK -f NICE_PRIMES.AWK
BEGIN {
    start = 500
    stop = 1000
    for (i=start; i<=stop; i++) {
      if (is_prime(i)) {
        s = i
        while (s >= 10) {
          s = sum_digits(s)
        }
        if (s ~ /^[2357]$/) {
          count++
          printf("%d %d\n",i,s)
        }
      }
    }
    printf("Nice primes %d-%d: %d\n",start,stop,count)
    exit(0)
}
function is_prime(x,  i) {
    if (x <= 1) {
      return(0)
    }
    for (i=2; i<=int(sqrt(x)); i++) {
      if (x % i == 0) {
        return(0)
      }
    }
    return(1)
}
function sum_digits(x,  sum,y) {
    while (x) {
      y = x % 10
      sum += y
      x = int(x/10)
    }
    return(sum)
}
Output:
509 5
547 7
563 5
569 2
587 2
599 5
601 7
617 5
619 7
641 2
653 5
659 2
673 7
677 2
691 7
709 7
727 7
743 5
761 5
797 5
821 2
839 2
853 7
857 2
887 5
907 7
911 2
929 2
941 5
947 2
977 5
983 2
997 7
Nice primes 500-1000: 33

BASIC

10 DEFINT A-Z: B=500: E=1000
20 DIM P(E): P(0)=-1: P(1)=-1
30 FOR I=2 TO SQR(E)
40 IF NOT P(I) THEN FOR J=I*2 TO E STEP I: P(J)=-1: NEXT
50 NEXT
60 FOR I=B TO E: IF P(I) GOTO 110
70 J=I
80 S=0
90 IF J>0 THEN S=S+J MOD 10: J=J\10: GOTO 90
100 IF S>9 THEN J=S: GOTO 80 ELSE IF NOT P(S) THEN PRINT I,
110 NEXT
Output:
 509           547           563           569           587
 599           601           617           619           641
 653           659           673           677           691
 709           727           743           761           797
 821           839           853           857           887
 907           911           929           941           947
 977           983           997

BCPL

get "libhdr"
manifest $(
    begin = 500
    end   = 1000
$)

let sieve(prime, top) be
$(  0!prime := false
    1!prime := false
    for i=2 to top do i!prime := true
    for i=2 to top/2
        if i!prime
        $(  let j = i*2
            while j <= top
            $(  j!prime := false
                j := j + i
            $)
        $)
$)

let digroot(n) = 
    n<10 -> n, 
    digroot(digsum(n))
and digsum(n) = 
    n<10 -> n,
    n rem 10 + digsum(n/10)

let nice(prime, n) = n!prime & digroot(n)!prime

let start() be
$(  let prime = getvec(end)
    sieve(prime, end)
    for i = begin to end
        if nice(prime, i) do
            writef("%N*N", i)
    freevec(prime)
$)
Output:
509
547
563
569
587
599
601
617
619
641
653
659
673
677
691
709
727
743
761
797
821
839
853
857
887
907
911
929
941
947
977
983
997


C

Translation of: C++
#include <stdbool.h>
#include <stdio.h>

bool is_prime(unsigned int n) {
    if (n < 2) {
        return false;
    }
    if (n % 2 == 0) {
        return n == 2;
    }
    if (n % 3 == 0) {
        return n == 3;
    }
    for (unsigned int p = 5; p * p <= n; p += 4) {
        if (n % p == 0) {
            return false;
        }
        p += 2;
        if (n % p == 0) {
            return false;
        }
    }
    return true;
}

unsigned int digital_root(unsigned int n) {
    return n == 0 ? 0 : 1 + (n - 1) % 9;
}

int main() {
    const unsigned int from = 500, to = 1000;
    unsigned int count = 0;
    unsigned int n;

    printf("Nice primes between %d and %d:\n", from, to);
    for (n = from; n < to; ++n) {
        if (is_prime(digital_root(n)) && is_prime(n)) {
            ++count;
            //std::cout << n << (count % 10 == 0 ? '\n' : ' ');
            printf("%d", n);
            if (count % 10 == 0) {
                putc('\n', stdout);
            } else {
                putc(' ', stdout);
            }
        }
    }
    printf("\n%d nice primes found.\n", count);

    return 0;
}
Output:
Nice primes between 500 and 1000:
509 547 563 569 587 599 601 617 619 641
653 659 673 677 691 709 727 743 761 797
821 839 853 857 887 907 911 929 941 947
977 983 997
33 nice primes found.

C++

#include <iostream>

bool is_prime(unsigned int n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (unsigned int p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

unsigned int digital_root(unsigned int n) {
    return n == 0 ? 0 : 1 + (n - 1) % 9;
}

int main() {
    const unsigned int from = 500, to = 1000;
    std::cout << "Nice primes between " << from << " and " << to << ":\n";
    unsigned int count = 0;
    for (unsigned int n = from; n < to; ++n) {
        if (is_prime(digital_root(n)) && is_prime(n)) {
            ++count;
            std::cout << n << (count % 10 == 0 ? '\n' : ' ');
        }
    }
    std::cout << '\n' << count << " nice primes found.\n";
}
Output:
Nice primes between 500 and 1000:
509 547 563 569 587 599 601 617 619 641
653 659 673 677 691 709 727 743 761 797
821 839 853 857 887 907 911 929 941 947
977 983 997 
33 nice primes found.

D

Translation of: C++
import std.stdio;

bool isPrime(uint n) {
    if (n < 2) {
        return false;
    }
    if (n % 2 == 0) {
        return n == 2;
    }
    if (n % 3 == 0) {
        return n == 3;
    }
    for (uint p = 5; p * p <= n; p += 4) {
        if (n % p == 0) {
            return false;
        }
        p += 2;
        if (n % p == 0) {
            return false;
        }
    }
    return true;
}

uint digitalRoot(uint n) {
    return n == 0 ? 0 : 1 + (n - 1) % 9;
}

void main() {
    immutable from = 500;
    immutable to = 1000;
    writeln("Nice primes between ", from, " and ", to, ':');
    uint count;
    foreach (n; from .. to) {
        if (isPrime(digitalRoot(n)) && isPrime(n)) {
            count++;
            write(n);
            if (count % 10 == 0) {
                writeln;
            } else {
                write(' ');
            }
        }
    }
    writeln;
    writeln(count, " nice primes found.");
}
Output:
Nice primes between 500 and 1000:
509 547 563 569 587 599 601 617 619 641
653 659 673 677 691 709 727 743 761 797
821 839 853 857 887 907 911 929 941 947
977 983 997
33 nice primes found.


Delphi

Works with: Delphi version 6.0


function IsPrime(N: int64): boolean;
{Fast, optimised prime test}
var I,Stop: int64;
begin
if (N = 2) or (N=3) then Result:=true
else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false
else
     begin
     I:=5;
     Stop:=Trunc(sqrt(N+0.0));
     Result:=False;
     while I<=Stop do
           begin
           if ((N mod I) = 0) or ((N mod (I + 2)) = 0) then exit;
           Inc(I,6);
           end;
     Result:=True;
     end;
end;



function SumDigits(N: integer): integer;
{Sum the integers in a number}
var T: integer;
begin
Result:=0;
repeat
	begin
	T:=N mod 10;
	N:=N div 10;
	Result:=Result+T;
	end
until N<1;
end;



function IsNiceNumber(N: integer): boolean;
{Return True if N is a nice number}
var Sum: integer;
begin
Result:=False;
{N must be primes}
if not IsPrime(N) then exit;
{Keep summing until one digit number}
Sum:=N;
repeat Sum:=SumDigits(Sum)
until Sum<10;
{Must be prime too}
Result:=IsPrime(Sum);
end;


procedure ShowNicePrimes(Memo: TMemo);
{Display Nice Primes between 501 and 999}
var I,Cnt: integer;
var S: string;
begin
Cnt:=0; S:='';
for I:=501 to 999 do
 if IsNiceNumber(I) then
	begin
	S:=S+Format('%4d',[i]);
	Inc(Cnt);
	if (Cnt mod 5)=0 then S:=S+#$0D#$0A;
	end;
Memo.Lines.Add(Format('Nice Primes: %3D',[Cnt]));
Memo.Lines.Add(S);
end;
Output:
Nice Primes:  33
 509 547 563 569 587
 599 601 617 619 641
 653 659 673 677 691
 709 727 743 761 797
 821 839 853 857 887
 907 911 929 941 947
 977 983 997


F#

This task uses Extensible Prime Generator (F#)

// Nice primes. Nigel Galloway: March 22nd., 2021
let fN g=1+((g-1)%9) in primes32()|>Seq.skipWhile((>)500)|>Seq.takeWhile((>)1000)|>Seq.filter(fN>>isPrime)|>Seq.iter(printf "%d "); printfn ""
Output:
509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997

Factor

Using the following formula to find the digital root of a base 10 number:

dr10(n) = 0                                 if n = 0,
dr10(n) = 1 + ((n - 1) mod 9)     if n ≠ 0.

(n = 0 may not need to be special-cased depending on the behavior of your language's modulo operator.)

USING: math math.primes prettyprint sequences ;

: digital-root ( m -- n ) 1 - 9 mod 1 + ;

500 1000 primes-between [ digital-root prime? ] filter .
Output:
V{
    509
    547
    563
    569
    587
    599
    601
    617
    619
    641
    653
    659
    673
    677
    691
    709
    727
    743
    761
    797
    821
    839
    853
    857
    887
    907
    911
    929
    941
    947
    977
    983
    997
}

Forth

Translation of: Factor
Works with: Gforth
: prime? ( n -- ? ) here + c@ 0= ;
: notprime! ( n -- ) here + 1 swap c! ;

: prime_sieve ( n -- )
  here over erase
  0 notprime!
  1 notprime!
  2
  begin
    2dup dup * >
  while
    dup prime? if
      2dup dup * do
        i notprime!
      dup +loop
    then
    1+
  repeat
  2drop ;

: digital_root ( m -- n ) 1 - 9 mod 1 + ;

: print_nice_primes ( m n -- )
  ." Nice primes between " dup . ." and " over 1 .r ." :" cr
  over prime_sieve
  0 -rot
  do
    i prime? if
      i digital_root prime? if
        i 3 .r
        1+ dup 10 mod 0= if cr else space then
      then
    then
  loop
  cr . ." nice primes found." cr ;

1000 500 print_nice_primes
bye
Output:
Nice primes between 500 and 1000:
509 547 563 569 587 599 601 617 619 641
653 659 673 677 691 709 727 743 761 797
821 839 853 857 887 907 911 929 941 947
977 983 997 
33 nice primes found. 

FreeBASIC

Function isPrime(Byval ValorEval As Integer) As Boolean
    If ValorEval <= 1 Then Return False
    For i As Integer = 2 To Int(Sqr(ValorEval))
        If ValorEval Mod i = 0 Then Return False
    Next i
    Return True
End Function

Dim As Integer column = 0, limit1 = 500, limit2 = 1000, sumn

Print !"Buenos n£meros entre"; limit1; " y"; limit2; !": \n"

For n As Integer = limit1 To limit2
    Dim As String strn = Str(n)
    
    Do
        sumn = 0
        For m As Integer = 1 To Len(strn)
            sumn += Val(Mid(strn,m,1))
        Next m
        strn = Str(sumn)
    Loop Until Len(strn) = 1
    
    If isPrime(n) And isPrime(sumn) Then
        column += 1
        Print Using " ###"; n;
        If column Mod 8 = 0 Then Print : End If
    End If
Next n

Print !"\n\n"; column; " buenos n£meros encontrados."
Sleep
Output:
Buenos números entre 500 y 1000:

 509 547 563 569 587 599 601 617
 619 641 653 659 673 677 691 709
 727 743 761 797 821 839 853 857
 887 907 911 929 941 947 977 983
 997

 33 buenos números encontrados.

Fōrmulæ

Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website.

In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.

Solution

Test case

Showing nice primes in the range 500 .. 1,000

Go

Translation of: Wren
package main

import "fmt"

func isPrime(n int) bool {
    switch {
    case n < 2:
        return false
    case n%2 == 0:
        return n == 2
    case n%3 == 0:
        return n == 3
    default:
        d := 5
        for d*d <= n {
            if n%d == 0 {
                return false
            }
            d += 2
            if n%d == 0 {
                return false
            }
            d += 4
        }
        return true
    }
}

func sumDigits(n int) int {
    sum := 0
    for n > 0 {
        sum += n % 10
        n /= 10
    }
    return sum
}

func main() {
    fmt.Println("Nice primes in the interval (500, 900) are:")
    c := 0
    for i := 501; i <= 999; i += 2 {
        if isPrime(i) {
            s := i
            for s >= 10 {
                s = sumDigits(s)
            }
            if s == 2 || s == 3 || s == 5 || s == 7 {
                c++
                fmt.Printf("%2d: %d -> Σ = %d\n", c, i, s)
            }
        }
    }
}
Output:
Same as Wren example.

Haskell

import Data.Char ( digitToInt ) 

isPrime :: Int -> Bool
isPrime n 
   |n == 2 = True
   |n == 1 = False
   |otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root]
   where
      root :: Int
      root = floor $ sqrt $ fromIntegral n

digitsum :: Int -> Int
digitsum n = sum $ map digitToInt $ show n

findSumn :: Int -> Int
findSumn n = until ( (== 1) . length . show ) digitsum n

isNicePrime :: Int -> Bool
isNicePrime n = isPrime n && isPrime ( findSumn n ) 

solution :: [Int]
solution = filter isNicePrime [501..999]
Output:
[509,547,563,569,587,599,601,617,619,641,653,659,673,677,691,709,727,743,761,797,821,839,853,857,887,907,911,929,941,947,977,983,997]

J

   primeQ=: 1&p:
   digital_root=: +/@:(10&#.inv)^:_   NB. sum the digits to convergence
   niceQ=: [: *./ [: primeQ (, digital_root)
   (#~niceQ&>)(+i.)500
509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997

   NB. testing only the primes on the range
   p:inv 500 1000  NB. index of the next largest prime in an ordered list of primes
95 168

   (#~ (2 3 5 7 e.~ digital_root&>)) p: 95 + i. 168 - 95
509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997

Java

Translation of: Kotlin
public class NicePrimes {
    private static boolean isPrime(long n) {
        if (n < 2) {
            return false;
        }
        if (n % 2 == 0L) {
            return n == 2L;
        }
        if (n % 3 == 0L) {
            return n == 3L;
        }

        var p = 5L;
        while (p * p <= n) {
            if (n % p == 0L) {
                return false;
            }
            p += 2;
            if (n % p == 0L) {
                return false;
            }
            p += 4;
        }
        return true;
    }

    private static long digitalRoot(long n) {
        if (n == 0) {
            return 0;
        }
        return 1 + (n - 1) % 9;
    }

    public static void main(String[] args) {
        final long from = 500;
        final long to = 1000;
        int count = 0;

        System.out.printf("Nice primes between %d and %d%n", from, to);
        long n = from;
        while (n < to) {
            if (isPrime(digitalRoot(n)) && isPrime(n)) {
                count++;
                System.out.print(n);
                if (count % 10 == 0) {
                    System.out.println();
                } else {
                    System.out.print(' ');
                }
            }

            n++;
        }
        System.out.println();
        System.out.printf("%d nice primes found.%n", count);
    }
}
Output:
Nice primes between 500 and 1000
509 547 563 569 587 599 601 617 619 641
653 659 673 677 691 709 727 743 761 797
821 839 853 857 887 907 911 929 941 947
977 983 997 
33 nice primes found.

jq

Works with: jq

Works with gojq, the Go implementation of jq

This entry uses `is_prime` as defined at Erdős-primes#jq.

def is_nice:
  # input: a non-negative integer
  def sumn:
    . as $in
    | tostring
    | if length == 1 then $in
      else explode | map([.] | implode | tonumber) | add | sumn
      end;

  is_prime and (sumn|is_prime);

# The task:
range(501; 1000) | select(is_nice)
Output:
509
547
563
569
587
599
601
617
619
641
653
659
673
677
691
709
727
743
761
797
821
839
853
857
887
907
911
929
941
947
977
983
997

Julia

See Strange_numbers#Julia for the filter_open_interval function.

using Primes

isnice(n, base=10) = isprime(n) && (mod1(n - 1, base - 1) + 1) in [2, 3, 5, 7, 11, 13, 17, 19]

filter_open_interval(500, 1000, isnice)
Output:
Finding numbers matching isnice for open interval (500, 1000):

509  547  563  569  587  599  601  617  619  641  653  659  673  677  691  709  727  743  
761  797  821  839  853  857  887  907  911  929  941  947  977  983  997

The total found was 33

Kotlin

Translation of: C
fun isPrime(n: Long): Boolean {
    if (n < 2) {
        return false
    }
    if (n % 2 == 0L) {
        return n == 2L
    }
    if (n % 3 == 0L) {
        return n == 3L
    }

    var p = 5
    while (p * p <= n) {
        if (n % p == 0L) {
            return false
        }
        p += 2
        if (n % p == 0L) {
            return false
        }
        p += 4
    }
    return true
}

fun digitalRoot(n: Long): Long {
    if (n == 0L) {
        return 0
    }
    return 1 + (n - 1) % 9
}

fun main() {
    val from = 500L
    val to = 1000L
    var count = 0

    println("Nice primes between $from and $to:")
    var n = from
    while (n < to) {
        if (isPrime(digitalRoot(n)) && isPrime(n)) {
            count += 1
            print(n)
            if (count % 10 == 0) {
                println()
            } else {
                print(' ')
            }
        }

        n += 1
    }
    println()
    println("$count nice primes found.")
}
Output:
Nice primes between 500 and 1000:
509 547 563 569 587 599 601 617 619 641
653 659 673 677 691 709 727 743 761 797
821 839 853 857 887 907 911 929 941 947
977 983 997 
33 nice primes found.

Lua

Translation of: C
function isPrime(n)
    if n < 2 then
        return false
    end
    if n % 2 == 0 then
        return n == 2
    end
    if n % 3 == 0 then
        return n == 3
    end

    local p = 5
    while p * p <= n do
        if n % p == 0 then
            return false
        end
        p = p + 2
        if n % p == 0 then
            return false
        end
        p = p + 4
    end
    return true
end

function digitalRoot(n)
    if n == 0 then
        return 0
    else
        return 1 + (n - 1) % 9
    end
end

from = 500
to = 1000
count = 0
print("Nice primes between " .. from .. " and " .. to)
n = from
while n < to do
    if isPrime(digitalRoot(n)) and isPrime(n) then
        count = count + 1
        io.write(n)
        if count % 10 == 0 then
            print()
        else
            io.write(' ')
        end
    end
    n = n + 1
end
print(count .. " nice primes found.")
Output:
Nice primes between 500 and 1000
509 547 563 569 587 599 601 617 619 641
653 659 673 677 691 709 727 743 761 797
821 839 853 857 887 907 911 929 941 947
977 983 997 33 nice primes found.

Mathematica/Wolfram Language

ClearAll[summ]
summ[n_] := FixedPoint[IntegerDigits /* Total, n]
Select[Range[501, 999], PrimeQ[#] \[And] PrimeQ[summ[#]] &]
Output:
{509, 547, 563, 569, 587, 599, 601, 617, 619, 641, 653, 659, 673, 677, 691, 709, 727, 743, 761, 797, 821, 839, 853, 857, 887, 907, 911, 929, 941, 947, 977, 983, 997}

Nim

import strutils, sugar

func isPrime(n: Positive): bool =
  if (n and 1) == 0: return n == 2
  var m = 3
  while m * m <= n:
    if n mod m == 0: return false
    inc m, 2
  result = true

func sumn(n: Positive): int =
  var n = n.int
  while n != 0:
    result += n mod 10
    n = n div 10

func isNicePrime(n: Positive): bool =
  if not n.isPrime: return false
  var n = n
  while n notin 1..9:
    n = sumn(n)
  result = n in [2, 3, 5, 7]

let list = collect(newSeq):
             for n in 501..999:
               if n.isNicePrime: n

echo "Found $1 nice primes between 501 and 999:".format(list.len)
for i, n in list:
  stdout.write n, if (i + 1) mod 10 == 0: '\n' else: ' '
echo()
Output:
Found 33 nice primes between 501 and 999:
509 547 563 569 587 599 601 617 619 641
653 659 673 677 691 709 727 743 761 797
821 839 853 857 887 907 911 929 941 947
977 983 997 

OCaml

After ruling out all multiples of three, mod 9 (the digital root) can only return {1, 2, 4, 5, 7, 8}. Adding 6 before calculating mod 9 makes all primes in the result even (and the composites odd), so (n + 6) mod 9 land 1 = 0 is sufficient for checking the digital root.

let is_nice_prime n =
  let rec test x =
    x * x > n || n mod x <> 0 && n mod (x + 2) <> 0 && test (x + 6)
  in
  if n < 5
  then n lor 1 = 3
  else n land 1 <> 0 && n mod 3 <> 0 && (n + 6) mod 9 land 1 = 0 && test 5

let () =
  Seq.(ints 500 |> take 500 |> filter is_nice_prime |> iter (Printf.printf " %u"))
  |> print_newline
Output:
 509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997

ooRexx

/* REXX */
n=1000
prime = .Array~new(n)~fill(.true)~~remove(1)
p.=0
Do i = 2 to n
  If prime[i] = .true Then Do
    Do j = i * i to n by i
      prime~remove(j)
      End
    p.i=1
    End
  End
z=0
ol=''
Do i=500 To 1000
  If p.i then Do
    dr=digroot(i)
    If p.dr Then Do
      ol=ol'  'i'('dr')'
      z=z+1
      If z//10=0 Then Do
        Say strip(ol)
        ol=''
        End
      End
    End
  End
Say strip(ol)
Say z 'nice primes in the range 500 to 1000'
Exit

digroot:
  Parse Arg s
  Do Until length(s)=1
    dr=0
    Do j=1 To length(s)
      dr=dr+substr(s,j,1)
      End
    s=dr
    End
  Return s
Output:
509(5)  547(7)  563(5)  569(2)  587(2)  599(5)  601(7)  617(5)  619(7)  641(2)
653(5)  659(2)  673(7)  677(2)  691(7)  709(7)  727(7)  743(5)  761(5)  797(5)
821(2)  839(2)  853(7)  857(2)  887(5)  907(7)  911(2)  929(2)  941(5)  947(2)
977(5)  983(2)  997(7)
33 nice primes in the range 500 to 1000

PARI/GP

nicePrimes( s, e ) = { local( m );
    forprime( p = s, e,
        m = p;                      \\
        while( m > 9,               \\   m == p mod 9
            m = sumdigits( m ) );   \\
        if( isprime( m ),
            print1( p, " " ) ) ); 
}

or

select( p -> isprime( p % 9 ), primes( [500, 1000] ))

Perl

Library: ntheory
use strict;
use warnings;

use ntheory 'is_prime';
use List::Util qw(sum);

sub digital_root {
    my ($n) = @_;
    do { $n = sum split '', $n } until 1 == length $n;
    $n
}

my($low, $high, $cnt, @nice_primes) = (500,1000);
is_prime($_) and is_prime(digital_root($_)) and push @nice_primes, $_ for $low+1 .. $high-1;

$cnt = @nice_primes;
print "Nice primes between $low and $high (total of $cnt):\n" .
(sprintf "@{['%5d' x $cnt]}", @nice_primes[0..$cnt-1]) =~ s/(.{55})/$1\n/gr;
Output:
Nice primes between 500 and 1000 (total of 33):
  509  547  563  569  587  599  601  617  619  641  653
  659  673  677  691  709  727  743  761  797  821  839
  853  857  887  907  911  929  941  947  977  983  997

Phix

Translation of: Factor
function pdr(integer n) return is_prime(n) and is_prime(1+remainder(n-1,9)) end function
sequence res = filter(tagset(1000,500),pdr)
printf(1,"%d nice primes found:\n  %s\n",{length(res),join_by(apply(res,sprint),1,11,"  ","\n  ")})
Output:
33 nice primes found:
  509  547  563  569  587  599  601  617  619  641  653
  659  673  677  691  709  727  743  761  797  821  839
  853  857  887  907  911  929  941  947  977  983  997

PHP

Translation of: Python
<?php
// Function to check if a number is prime
function isPrime($n) {
    if ($n <= 1) {
        return false;
    }
    for ($i = 2; $i <= sqrt($n); $i++) {
        if ($n % $i == 0) {
            return false;
        }
    }
    return true;
}

// Function to sum the digits of a number until the sum is a single digit
function sumOfDigits($n) {
    while ($n > 9) {
        $sum = 0;
        while ($n > 0) {
            $sum += $n % 10;
            $n = (int)($n / 10);
        }
        $n = $sum;
    }
    return $n;
}

function findNicePrimes($lower_limit=501, $upper_limit=1000) {
	// Find all Nice primes within the specified range 
    $nice_primes = array();
    for ($n = $lower_limit; $n < $upper_limit; $n++) {
        if (isPrime($n)) {
            $sumn = sumOfDigits($n);
            if (isPrime($sumn)) {
                array_push($nice_primes, $n);
            }
        }
    }
    return $nice_primes;
}
// Main loop to find and print "Nice Primes"
$nice_primes = findNicePrimes();
foreach ($nice_primes as $prime) {
    echo $prime . " ";
}
?>
Output:
509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997

Python

def is_prime(n):
    """Check if a number is prime."""
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

def sum_of_digits(n):
    """Calculate the repeated sum of digits until the sum's length is 1."""
    while n > 9:
        n = sum(int(digit) for digit in str(n))
    return n

def find_nice_primes(lower_limit=501, upper_limit=1000):
    """Find all Nice primes within the specified range."""
    nice_primes = []
    for n in range(lower_limit, upper_limit):
        if is_prime(n):
            sumn = sum_of_digits(n)
            if is_prime(sumn):
                nice_primes.append(n)
    return nice_primes

# Example usage
nice_primes = find_nice_primes()
print(nice_primes)
Output:
[509, 547, 563, 569, 587, 599, 601, 617, 619, 641, 653, 659, 673, 677, 691, 709, 727, 743, 761, 797, 821, 839, 853, 857, 887, 907, 911, 929, 941, 947, 977, 983, 997]

PL/0

var   n, sum, prime, i;
procedure sumdigitsofn;
    var v, vover10;
    begin
        sum := 0;
        v   := n;
        while v > 0 do begin
            vover10 := v / 10;
            sum := sum + ( v - ( vover10 * 10 ) );
            v := vover10
        end
    end;
procedure isnprime;
    var p;
    begin
        prime := 1;
        if n < 2 then prime := 0;
        if n > 2 then begin
            prime := 0;
            if odd( n ) then prime := 1;
            p := 3;
            while p * p <= n * prime do begin
               if n - ( ( n / p ) * p ) = 0 then prime := 0;
               p := p + 2;
            end
        end
    end;
begin
    i := 500;
    while i < 999 do begin
        i := i + 1;
        n := i;
        call isnprime;
        if prime = 1 then begin
            sum := n;
            while sum > 9 do begin
                call sumdigitsofn;
                n := sum
            end;
            if sum = 2 then ! i;
            if sum = 3 then ! i;
            if sum = 5 then ! i;
            if sum = 7 then ! i
        end
    end
end.
Output:

Note: PL/0 can only output one value per line, to avoid a long output, the results have been manually combined to 7 per line.

        509        547        563        569        587        599        601
        617        619        641        653        659        673        677
        691        709        727        743        761        797        821
        839        853        857        887        907        911        929
        941        947        977        983        997

PL/M

Translation of: ALGOL 68
100H:  /* FIND NICE PRIMES - PRIMES WHOSE DIGITAL ROOT IS ALSO PRIME */
   BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
      DECLARE FN BYTE, ARG ADDRESS;
      GOTO 5;
   END BDOS;
   PRINT$CHAR:   PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
   PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
   PRINT$NUMBER: PROCEDURE( N );
      DECLARE N ADDRESS;
      DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
      V = N;
      W = LAST( N$STR );
      N$STR( W ) = '$';
      N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      DO WHILE( ( V := V / 10 ) > 0 );
         N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      END;
      CALL PRINT$STRING( .N$STR( W ) );
   END PRINT$NUMBER;
   /* INTEGER SUARE ROOT: BASED ON THE ONE IN THE PL/M FOR FROBENIUS NUMBERS */
   SQRT: PROCEDURE( N )ADDRESS;
      DECLARE ( N, X0, X1 ) ADDRESS;
      IF N <= 3 THEN DO;
          IF N = 0 THEN X0 = 0; ELSE X0 = 1;
          END;
      ELSE DO;
         X0 = SHR( N, 1 );
         DO WHILE( ( X1 := SHR( X0 + ( N / X0 ), 1 ) ) < X0 );
            X0 = X1;
         END;
      END;
      RETURN X0;
   END SQRT;
   DECLARE MIN$PRIME LITERALLY '501';
   DECLARE MAX$PRIME LITERALLY '999';
   DECLARE DCL$PRIME LITERALLY '1000';
   DECLARE FALSE     LITERALLY '0';
   DECLARE TRUE      LITERALLY '1';
   /* SIEVE THE PRIMES TO MAX$PRIME */
   DECLARE ( I, S ) ADDRESS;
   DECLARE PRIME ( DCL$PRIME )BYTE;
   PRIME( 1 ) = FALSE; PRIME( 2 ) = TRUE;
   DO I = 3 TO LAST( PRIME ) BY 2; PRIME( I ) = TRUE;  END;
   DO I = 4 TO LAST( PRIME ) BY 2; PRIME( I ) = FALSE; END;
   DO I = 3 TO SQRT( MAX$PRIME );
      IF PRIME( I ) THEN DO;
         DO S = I * I TO LAST( PRIME ) BY I + I;PRIME( S ) = FALSE; END;
      END;
   END;
   /* FIND THE NICE PRIMES */
   DECLARE NICE$COUNT ADDRESS;
   NICE$COUNT = 0;
   DO I = MIN$PRIME TO MAX$PRIME;
      IF PRIME( I ) THEN DO;
         /* HAVE A PRIME */
         DECLARE DIGIT$SUM BYTE, V ADDRESS;
         DIGIT$SUM = LOW( V := I );
         DO WHILE( V > 9 );
            DIGIT$SUM = 0;
            DO WHILE( V > 0 );
               DIGIT$SUM = DIGIT$SUM + ( V MOD 10 );
               V = V / 10;
            END;
            V = DIGIT$SUM;
         END;
         IF PRIME( DIGIT$SUM ) THEN DO;
            /* THE DIGITAL ROOT IS PRIME */
            NICE$COUNT = NICE$COUNT + 1;
            CALL PRINT$CHAR( ' ' );
            CALL PRINT$NUMBER( I );
            CALL PRINT$CHAR( '(' );
            CALL PRINTCHAR( DIGIT$SUM + '0' );
            CALL PRINT$CHAR( ')' );
            IF NICE$COUNT MOD 12 = 0 THEN DO;
               CALL PRINT$STRING( .( 0DH, 0AH, '$' ) );
            END;
         END;
      END;
   END;
EOF
Output:
 509(5) 547(7) 563(5) 569(2) 587(2) 599(5) 601(7) 617(5) 619(7) 641(2) 653(5) 659(2)
 673(7) 677(2) 691(7) 709(7) 727(7) 743(5) 761(5) 797(5) 821(2) 839(2) 853(7) 857(2)
 887(5) 907(7) 911(2) 929(2) 941(5) 947(2) 977(5) 983(2) 997(7)

Quackery

eratosthenes and isprime are defined at Sieve of Eratosthenes#Quackery.

  1000 eratosthenes

  [ 1 - 9 mod 1+ ]          is digitalroot ( n --> n )

  [ dup digitalroot isprime
    swap isprime and ]      is niceprime   ( n --> b )

  500 times
    [ i^ 500 + niceprime if
        [ i^ 500 + echo sp ] ]
Output:
509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997 

Raku

sub digroot ($r) { .tail given $r, { [+] .comb } ... { .chars == 1 } }
my @is-nice = lazy (0..*).map: { .&is-prime && .&digroot.&is-prime ?? $_ !! False };
say @is-nice[500 ^..^ 1000].grep(*.so).batch(11)».fmt("%4d").join: "\n";
Output:
 509  547  563  569  587  599  601  617  619  641  653
 659  673  677  691  709  727  743  761  797  821  839
 853  857  887  907  911  929  941  947  977  983  997

Alternately, with somewhat better separation of concerns.

sub digroot ($r) { ($r, { .comb.sum } … { .chars == 1 }).tail }
sub is-nice ($_) { .is-prime && .&digroot.is-prime }
say (500 ^..^ 1000).grep( *.&is-nice ).batch(11)».fmt("%4d").join: "\n";

Same output.

REXX

/*REXX program finds and displays  nice primes, primes whose digital root is also prime.*/
parse arg lo hi cols .                           /*obtain optional argument from the CL.*/
if   lo=='' |   lo==","  then   lo=  500         /*Not specified?  Then use the default.*/
if   hi=='' |   hi==","  then   hi= 1000         /* "      "         "   "   "     "    */
if cols=='' | cols==","  then cols=   10         /* "      "         "   "   "     "    */
call genP                                        /*build array of semaphores for primes.*/
w= 10                                            /*width of a number in any column.     */
               title= ' nice primes that are between '   commas(lo)   " and "   commas(hi)
if cols>0 then say ' index │'center(title   ' (not inclusive)',   1 + cols*(w+1)     )
if cols>0 then say '───────┼'center(""                         ,  1 + cols*(w+1), '─')
found= 0;                    idx= 1              /*initialize # of nice primes and index*/
$=                                               /*a list of  nice  primes  (so far).   */
     do j=lo+1  to  hi-1;  if \!.j  then iterate /*search for  nice  primes within range*/
     digRoot= 1   +   (j - 1) // 9               /*obtain the digital root of  J.       */
     if \!.digRoot  then iterate                 /*Is digRoot prime?   No, then skip it.*/
     found= found + 1                            /*bump the number of  nice  primes.    */
     if cols<0             then iterate          /*Build the list  (to be shown later)? */
     c= commas(j)                                /*maybe add commas to the number.      */
     $= $ right(c, max(w, length(c) ) )          /*add a nice prime ──► list, allow big#*/
     if found//cols\==0    then iterate          /*have we populated a line of output?  */
     say center(idx, 7)'│'  substr($, 2);   $=   /*display what we have so far  (cols). */
     idx= idx + cols                             /*bump the  index  count for the output*/
     end   /*j*/

if $\==''  then say center(idx, 7)"│"  substr($, 2)  /*possible display residual output.*/
if cols>0 then say '───────┴'center(""                         ,  1 + cols*(w+1), '─')
say
say 'Found '       commas(found)      title      ' (not inclusive).'
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?;  do jc=length(?)-3  to 1  by -3; ?=insert(',', ?, jc); end;  return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP:        @.1=2; @.2=3; @.3=5; @.4=7;  @.5=11 /*define some low primes.              */
      !.=0;  !.2=1; !.3=1; !.5=1; !.7=1;  !.11=1 /*   "     "   "    "     semaphores.  */
                           #=5;   s.#= @.# **2   /*number of primes so far;     prime². */
        do j=@.#+2  by 2  to hi                  /*find odd primes from here on.        */
        parse var j '' -1 _; if     _==5  then iterate  /*J divisible by 5?  (right dig)*/
                             if j// 3==0  then iterate  /*"     "      " 3?             */
                             if j// 7==0  then iterate  /*"     "      " 7?             */
                                                 /* [↑]  the above five lines saves time*/
               do k=5  while s.k<=j              /* [↓]  divide by the known odd primes.*/
               if j // @.k == 0  then iterate j  /*Is  J ÷ X?  Then not prime.     ___  */
               end   /*k*/                       /* [↑]  only process numbers  ≤  √ J   */
        #= #+1;    @.#= j;    s.#= j*j;   !.j= 1 /*bump # of Ps; assign next P;  P²; P# */
        end          /*j*/;   return
output   when using the default inputs:
 index │                         nice primes that are between  500  and  1,000  (not inclusive)
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
   1   │        509        547        563        569        587        599        601        617        619        641
  11   │        653        659        673        677        691        709        727        743        761        797
  21   │        821        839        853        857        887        907        911        929        941        947
  31   │        977        983        997
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────

Found  33  nice primes that are between  500  and  1,000  (not inclusive).

Ring

load "stdlib.ring"

num = 0
limit1 = 500
limit2 = 1000

see "working..." + nl
see "Nice numbers are:" + nl

for n = limit1 to limit2
    strn = string(n)
    while true
          sumn = 0
          for m = 1 to len(strn)
              sumn = sumn + number(strn[m])
          next
          if len(string(sumn)) = 1
             exit
          ok
          strn = string(sumn)
    end
    if isprime(n) and isprime(sumn)
       num = num + 1
       see "" + num + ": " + n + " > Σ = " + sumn + nl
    ok
next

see "done..." + nl
Output:
working...
Nice numbers are:
1: 509 > Σ = 5
2: 547 > Σ = 7
3: 563 > Σ = 5
4: 569 > Σ = 2
5: 587 > Σ = 2
6: 599 > Σ = 5
7: 601 > Σ = 7
8: 617 > Σ = 5
9: 619 > Σ = 7
10: 641 > Σ = 2
11: 653 > Σ = 5
12: 659 > Σ = 2
13: 673 > Σ = 7
14: 677 > Σ = 2
15: 691 > Σ = 7
16: 709 > Σ = 7
17: 727 > Σ = 7
18: 743 > Σ = 5
19: 761 > Σ = 5
20: 797 > Σ = 5
21: 821 > Σ = 2
22: 839 > Σ = 2
23: 853 > Σ = 7
24: 857 > Σ = 2
25: 887 > Σ = 5
26: 907 > Σ = 7
27: 911 > Σ = 2
28: 929 > Σ = 2
29: 941 > Σ = 5
30: 947 > Σ = 2
31: 977 > Σ = 5
32: 983 > Σ = 2
33: 997 > Σ = 7
done...

RPL

≪ { } 500
   DO
      NEXTPRIME
      IF DUP 1 - 9 MOD 1 + ISPRIME? THEN
         SWAP OVER + SWAP END
   UNTIL DUP 1000 ≥ END
   DROP
≫ 'TASK' STO
Output:
1: { 509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997 }

Ruby

require 'prime'

class Integer
  def dig_root = (1+(self-1).remainder(9))
  def nice? = prime? && dig_root.prime?
end

p (500..1000).select(&:nice?)
Output:
[509, 547, 563, 569, 587, 599, 601, 617, 619, 641, 653, 659, 673, 677, 691, 709, 727, 743, 761, 797, 821, 839, 853, 857, 887, 907, 911, 929, 941, 947, 977, 983, 997]

Rust

Translation of: Factor
// [dependencies]
// primal = "0.3"

fn digital_root(n: u64) -> u64 {
    if n == 0 {
        0
    } else {
        1 + (n - 1) % 9
    }
}

fn nice_primes(from: usize, to: usize) {
    primal::Sieve::new(to)
        .primes_from(from)
        .take_while(|x| *x < to)
        .filter(|x| primal::is_prime(digital_root(*x as u64)))
        .for_each(|x| println!("{}", x));
}

fn main() {
    nice_primes(500, 1000);
}
Output:
509
547
563
569
587
599
601
617
619
641
653
659
673
677
691
709
727
743
761
797
821
839
853
857
887
907
911
929
941
947
977
983
997

Seed7

$ include "seed7_05.s7i";

const func boolean: isPrime (in integer: number) is func
  result
    var boolean: prime is FALSE;
  local
    var integer: upTo is 0;
    var integer: testNum is 3;
  begin
    if number = 2 then
      prime := TRUE;
    elsif odd(number) and number > 2 then
      upTo := sqrt(number);
      while number rem testNum <> 0 and testNum <= upTo do
        testNum +:= 2;
      end while;
      prime := testNum > upTo;
    end if;
  end func;

const proc: main is func
  local
    var integer: n is 0;
  begin
    for n range 501 to 999 step 2 do
      if isPrime(n) and 1 + ((n - 1) rem 9) in {2, 3, 5, 7} then
        write(n <& " ");
      end if;
    end for;
  end func;
Output:
509 547 563 569 587 599 601 617 619 641 653 659 673 677 691 709 727 743 761 797 821 839 853 857 887 907 911 929 941 947 977 983 997

Sidef

func digital_root(n, base=10) {
    while (n.len(base) > 1) {
        n = n.sumdigits(base)
    }
    return n
}

say primes(500, 1000).grep { digital_root(_).is_prime }
Output:
[509, 547, 563, 569, 587, 599, 601, 617, 619, 641, 653, 659, 673, 677, 691, 709, 727, 743, 761, 797, 821, 839, 853, 857, 887, 907, 911, 929, 941, 947, 977, 983, 997]

Wren

Library: Wren-math
Library: Wren-iterate
Library: Wren-fmt
import "./math" for Int
import "./iterate" for Stepped
import "./fmt" for Fmt

var sumDigits = Fn.new { |n|
    var sum = 0
    while (n > 0) {
        sum = sum + (n % 10)
        n = (n/10).floor
    }
    return sum
}

System.print("Nice primes in the interval (500, 900) are:")
var c = 0
for (i in Stepped.new(501..999, 2)) {
    if (Int.isPrime(i)) {
        var s = i
        while (s >= 10) s = sumDigits.call(s)
        if (Int.isPrime(s)) {
            c = c + 1
            Fmt.print("$2d: $d -> Σ = $d", c, i, s)
        }
    }
}
Output:
Nice primes in the interval (500, 900) are:
 1: 509 -> Σ = 5
 2: 547 -> Σ = 7
 3: 563 -> Σ = 5
 4: 569 -> Σ = 2
 5: 587 -> Σ = 2
 6: 599 -> Σ = 5
 7: 601 -> Σ = 7
 8: 617 -> Σ = 5
 9: 619 -> Σ = 7
10: 641 -> Σ = 2
11: 653 -> Σ = 5
12: 659 -> Σ = 2
13: 673 -> Σ = 7
14: 677 -> Σ = 2
15: 691 -> Σ = 7
16: 709 -> Σ = 7
17: 727 -> Σ = 7
18: 743 -> Σ = 5
19: 761 -> Σ = 5
20: 797 -> Σ = 5
21: 821 -> Σ = 2
22: 839 -> Σ = 2
23: 853 -> Σ = 7
24: 857 -> Σ = 2
25: 887 -> Σ = 5
26: 907 -> Σ = 7
27: 911 -> Σ = 2
28: 929 -> Σ = 2
29: 941 -> Σ = 5
30: 947 -> Σ = 2
31: 977 -> Σ = 5
32: 983 -> Σ = 2
33: 997 -> Σ = 7

XPL0

func IntLen(N);         \Return number of digits in N
int  N, I;
for I:= 1 to 10 do
    [N:= N/10;
    if N = 0 then return I;
    ];

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 SumDigits(N);      \Return sum of digits in N
int  N, Sum;
[Sum:= 0;
repeat  N:= N/10;
        Sum:= Sum + rem(0);
until   N=0;
return Sum;
];

int  C, N, SumN;
[C:= 0;
for N:= 501 to 999 do
    if IsPrime(N) then
        [SumN:= N;
        repeat  SumN:= SumDigits(SumN);
        until   IntLen(SumN) = 1;
        if IsPrime(SumN) then
            [IntOut(0, N);
            C:= C+1;
            if rem (C/10) then ChOut(0, ^ ) else CrLf(0);
            ];
        ];
]
Output:
509 547 563 569 587 599 601 617 619 641
653 659 673 677 691 709 727 743 761 797
821 839 853 857 887 907 911 929 941 947
977 983 997