Palindromic primes: Difference between revisions

Add Factor
(→‎{{header|Raku}}: Add a Raku example)
(Add Factor)
Line 5:
Find and show all palindromic primes &nbsp; <big>'''n'''</big>, &nbsp; &nbsp; where &nbsp; <big> '''n &nbsp; &lt; &nbsp; 1000''' </big>
<br><br>
 
=={{header|Factor}}==
A simple solution that suffices for the task:
{{works with|Factor|0.99 2021-02-05}}
<lang factor>USING: kernel math.primes present prettyprint sequences ;
 
1000 primes-upto [ present dup reverse = ] filter stack.</lang>
{{out}}
<pre style="height:14em">
2
3
5
7
11
101
131
151
181
191
313
353
373
383
727
757
787
797
919
929
</pre>
A much more efficient solution that generates palindromic numbers directly and filters primes from them:
=={{header|Factor}}==
{{works with|Factor|0.99 2021-02-05}}
<lang factor>USING: io kernel lists lists.lazy math math.functions
math.primes math.ranges prettyprint sequences
tools.memory.private ;
 
! Create a palindrome from its base natural number.
: create-palindrome ( n odd? -- m )
dupd [ 10 /i ] when swap [ over 0 > ]
[ 10 * [ 10 /mod ] [ + ] bi* ] while nip ;
! Create an ordered infinite lazy list of palindromic numbers.
: lpalindromes ( -- l )
0 lfrom [
10 swap ^ dup 10 * [a,b)
[ [ t create-palindrome ] map ]
[ [ f create-palindrome ] map ] bi
[ sequence>list ] bi@ lappend
] lmap-lazy lconcat ;
 
: lpalindrome-primes ( -- list )
lpalindromes [ prime? ] lfilter ;
 
"10,000th palindromic prime:" print
9999 lpalindrome-primes lnth commas print nl
 
"Palindromic primes less than 1,000:" print
lpalindrome-primes [ 1000 < ] lwhile [ . ] leach</lang>
{{out}}
<pre style="height:14em">
10,000th palindromic prime:
13,649,694,631
 
Palindromic primes less than 1,000:
2
3
5
7
11
101
131
151
181
191
313
353
373
383
727
757
787
797
919
929
</pre>
 
=={{header|Raku}}==
1,827

edits