I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

Palindromic primes

From Rosetta Code
Palindromic 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

Find and show all palindromic primes   n,     where   n   <   1000

AWK[edit]

 
# syntax: GAWK -f PALINDROMIC_PRIMES.AWK
BEGIN {
start = 1
stop = 999
for (i=start; i<=stop; i++) {
if (is_prime(i) && reverse(i) == i) {
printf("%d ",i)
count++
}
}
printf("\nPalindromic 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 reverse(str, i,rts) {
for (i=length(str); i>=1; i--) {
rts = rts substr(str,i,1)
}
return(rts)
}
 
Output:
2 3 5 7 11 101 131 151 181 191 313 353 373 383 727 757 787 797 919 929
Palindromic primes 1-999: 20

Factor[edit]

Simple[edit]

A simple solution that suffices for the task:

Works with: Factor version 0.99 2021-02-05
USING: kernel math.primes present prettyprint sequences ;
 
1000 primes-upto [ present dup reverse = ] filter stack.
Output:
2
3
5
7
11
101
131
151
181
191
313
353
373
383
727
757
787
797
919
929

Fast[edit]

A much more efficient solution that generates palindromic numbers directly and filters primes from them:

Works with: Factor version 0.99 2021-02-05
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 ] [email protected] 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
Output:
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

FreeBASIC[edit]

#include "isprime.bas"
 
function is_pal( s as string ) as boolean
dim as integer i, n = len(s)
for i = 1 to n\2
if mid(s,i,1)<>mid(s,n-i+1,1) then return false
next i
return true
end function
 
for i as uinteger = 2 to 999
if is_pal( str(i) ) andalso isprime(i) then print i;" ";
next i : print
Output:

2 3 5 7 11 101 131 151 181 191 313 353 373 383 727 757 787 797 919 929

Go[edit]

Translation of: Wren
Library: Go-rcu
package main
 
import (
"fmt"
"rcu"
)
 
func reversed(n int) int {
rev := 0
for n > 0 {
rev = rev*10 + n%10
n /= 10
}
return rev
}
 
func main() {
primes := rcu.Primes(99999)
var pals []int
for _, p := range primes {
if p == reversed(p) {
pals = append(pals, p)
}
}
fmt.Println("Palindromic primes under 1,000:")
var smallPals, bigPals []int
for _, p := range pals {
if p < 1000 {
smallPals = append(smallPals, p)
} else {
bigPals = append(bigPals, p)
}
}
rcu.PrintTable(smallPals, 10, 3, false)
fmt.Println()
fmt.Println(len(smallPals), "such primes found.")
 
fmt.Println("\nAdditional palindromic primes under 100,000:")
rcu.PrintTable(bigPals, 10, 6, true)
fmt.Println()
fmt.Println(len(bigPals), "such primes found,", len(pals), "in all.")
}
Output:
Same as Wren entry.

Haskell[edit]

import Data.Numbers.Primes
 
palindromicPrimes :: [Integer]
palindromicPrimes =
filter (((==) <*> reverse) . show) primes
 
main :: IO ()
main =
mapM_ print $
takeWhile
(1000 >)
palindromicPrimes
Output:
2
3
5
7
11
101
131
151
181
191
313
353
373
383
727
757
787
797
919
929

Julia[edit]

Generator method.

using Primes
 
parray = [2, 3, 5, 7, 9, 11]
 
results = vcat(parray, filter(isprime, [100j + 10i + j for i in 0:9, j in 1:9]))
 
println(results)
 
Output:
[2, 3, 5, 7, 9, 11, 101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929]

Perl[edit]

#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Palindromic_primes
use warnings;
 
$_ == reverse and (1 x $_ ) !~ /^(11+)\1+$/ and print "$_\n" for 2 .. 1e3;
Output:

2 3 5 7 11 101 131 151 181 191 313 353 373 383 727 757 787 797 919 929

Phix[edit]

filter primes for palindromicness[edit]

function palindrome(string s) return s=reverse(s) end function
for l=3 to 5 by 2 do
    integer limit = power(10,l) -- 1000 then 100000
    sequence res = get_primes_le(limit)
    res = apply(true,sprintf,{{"%d"},res})
    res = filter(res,palindrome)
    string s = join(shorten(res,"",5))
    printf(1,"found %d < %,d: %s\n",{length(res),limit,s})
end for
Output:
found 20 < 1,000: 2 3 5 7 11 ... 757 787 797 919 929
found 113 < 100,000: 2 3 5 7 11 ... 97379 97579 97879 98389 98689

filter palindromes for primality[edit]

sequence r = {}
for l=2 to 3 do
    for i=1 to power(10,l) do
        string s = sprintf("%d",i)
        integer t = to_number(s&reverse(s[1..$-1])),
                u = to_number(s&reverse(s))
        if is_prime(t) then r &= t end if
        if is_prime(u) then r &= u end if
    end for
    r = unique(r)
    string s = join(shorten(apply(true,sprintf,{{"%d"},r}),"",5))
    printf(1,"found %d < %,d: %s\n",{length(r),power(10,l*2-1),s})
end for

Same output. Didn't actually test if this way was any faster, but expect it would be.

Python[edit]

A non-finite generator of palindromic primes – one of many approaches to solving this problem in Python.

'''Palindromic primes'''
 
from itertools import takewhile
 
 
# palindromicPrimes :: Generator [Int]
def palindromicPrimes():
'''An infinite stream of palindromic primes'''
def p(n):
s = str(n)
return s == s[::-1]
return (n for n in primes() if p(n))
 
 
# ------------------------- TEST -------------------------
def main():
'''Palindromic primes below 1000'''
print('\n'.join(
str(x) for x in takewhile(
lambda n: 1000 > n,
palindromicPrimes()
)
))
 
 
# ----------------------- GENERIC ------------------------
 
# primes :: [Int]
def primes():
''' Non finite sequence of prime numbers.
'''

n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
 
 
# MAIN ---
if __name__ == '__main__':
main()
 
Output:
2
3
5
7
11
101
131
151
181
191
313
353
373
383
727
757
787
797
919
929

Raku[edit]

say "{+$_} matching numbers:\n{.batch(10)».fmt('%3d').join: "\n"}"
given (^1000).grep: { .is-prime and $_ eq .flip };
Output:
20 matching numbers:
  2   3   5   7  11 101 131 151 181 191
313 353 373 383 727 757 787 797 919 929

REXX[edit]

/*REXX program  finds and displays  palindromic primes  for all  N  < 1000.             */
parse arg hi cols . /*obtain optional argument from the CL.*/
if hi=='' | hi=="," then hi= 1000 /*Not specified? Then use the default.*/
if cols=='' | cols=="," then cols= 10 /* " " " " " " */
call genP /*build array of semaphores for primes.*/
w= max(8, length( commas(hi) ) ) /*max width of a number in any column. */
@pal= ' palindromic primes that are < ' commas(hi)
if cols>0 then say ' index │'center(@pal, 1 + cols*(w+1) )
if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─')
pals= 0; idx= 1 /*define # of palindromic primes & idx.*/
$= /*a list of palindromic primes so far).*/
do j=1 for # /*search for palindromic primes. */
if @.j\==reverse(@.j) then iterate /*Not a palindromic prime? Then skip. */
pals= pals + 1 /*bump the number of palindromic primes*/
if cols==0 then iterate /*Build the list (to be shown later)? */
$= $ right( commas(@.j), w) /*add a palindromic prime ──► $ list.*/
if pals//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(pals) @pal
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: !.= 0; hprime= copies(9, length(hi) ) /*placeholders for primes (semaphores).*/
@.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */
 !.2=1;  !.3=1;  !.5=1;  !.7=1;  !.11=1 /* " " " " flags. */
#=5; s.#= @.# **2 /*number of primes so far; prime². */
/* [↓] generate more primes ≤ high.*/
do [email protected].#+2 by 2 to hprime /*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 3 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 │                           palindromic primes that are  <  1,000
───────┼───────────────────────────────────────────────────────────────────────────────────────────
   1   │        2        3        5        7       11      101      131      151      181      191
  11   │      313      353      373      383      727      757      787      797      919      929
───────┴───────────────────────────────────────────────────────────────────────────────────────────

Found  20  palindromic primes that are  <  1,000
output   when using the input of:     100000
 index │                          palindromic primes that are  <  100,000
───────┼───────────────────────────────────────────────────────────────────────────────────────────
   1   │        2        3        5        7       11      101      131      151      181      191
  11   │      313      353      373      383      727      757      787      797      919      929
  21   │   10,301   10,501   10,601   11,311   11,411   12,421   12,721   12,821   13,331   13,831
  31   │   13,931   14,341   14,741   15,451   15,551   16,061   16,361   16,561   16,661   17,471
  41   │   17,971   18,181   18,481   19,391   19,891   19,991   30,103   30,203   30,403   30,703
  51   │   30,803   31,013   31,513   32,323   32,423   33,533   34,543   34,843   35,053   35,153
  61   │   35,353   35,753   36,263   36,563   37,273   37,573   38,083   38,183   38,783   39,293
  71   │   70,207   70,507   70,607   71,317   71,917   72,227   72,727   73,037   73,237   73,637
  81   │   74,047   74,747   75,557   76,367   76,667   77,377   77,477   77,977   78,487   78,787
  91   │   78,887   79,397   79,697   79,997   90,709   91,019   93,139   93,239   93,739   94,049
  101  │   94,349   94,649   94,849   94,949   95,959   96,269   96,469   96,769   97,379   97,579
  111  │   97,879   98,389   98,689
───────┴───────────────────────────────────────────────────────────────────────────────────────────

Found  113  palindromic primes that are  <  100,000

Ring[edit]

 
load "stdlib.ring"
 
see "working..." + nl
see "Palindromic primes are:" + nl
row = 0
limit1 = 1000
limit2 = 100000
 
palindromicPrimes(limit1)
 
see "Found " + row + " palindromic primes" + nl + nl
see "palindromic primes that are < 100,000" + nl
 
palindromicPrimes(limit2)
 
see nl + "Found " + row + " palindromic primes that are < 100,000" + nl
see "done..." + nl
 
func palindromicPrimes(limit)
row = 0
for n = 1 to limit
strn = string(n)
if ispalindrome(strn) and isprime(n)
row = row + 1
see "" + n + " "
if row%5 = 0
see nl
ok
ok
next
 
Output:
working...
Palindromic primes are:
2 3 5 7 11 
101 131 151 181 191 
313 353 373 383 727 
757 787 797 919 929 
Found 20 palindromic primes

palindromic primes that are  <  100,000
2 3 5 7 11 
101 131 151 181 191 
313 353 373 383 727 
757 787 797 919 929 
10301 10501 10601 11311 11411 
12421 12721 12821 13331 13831 
13931 14341 14741 15451 15551 
16061 16361 16561 16661 17471 
17971 18181 18481 19391 19891 
19991 30103 30203 30403 30703 
30803 31013 31513 32323 32423 
33533 34543 34843 35053 35153 
35353 35753 36263 36563 37273 
37573 38083 38183 38783 39293 
70207 70507 70607 71317 71917 
72227 72727 73037 73237 73637 
74047 74747 75557 76367 76667 
77377 77477 77977 78487 78787 
78887 79397 79697 79997 90709 
91019 93139 93239 93739 94049 
94349 94649 94849 94949 95959 
96269 96469 96769 97379 97579 
97879 98389 98689 
Found 113 palindromic primes that are < 100,000
done...

Wren[edit]

Library: Wren-math
Library: Wren-fmt
Library: Wren-seq
import "/math" for Int
import "/fmt" for Fmt
import "/seq" for Lst
 
var reversed = Fn.new { |n|
var rev = 0
while (n > 0) {
rev = rev * 10 + n % 10
n = (n/10).floor
}
return rev
}
 
var primes = Int.primeSieve(99999)
var pals = []
for (p in primes) {
if (p == reversed.call(p)) pals.add(p)
}
System.print("Palindromic primes under 1,000:")
var smallPals = pals.where { |p| p < 1000 }.toList
for (chunk in Lst.chunks(smallPals, 10)) Fmt.print("$3d", chunk)
System.print("\n%(smallPals.count) such primes found.")
 
System.print("\nAdditional palindromic primes under 100,000:")
var bigPals = pals.where { |p| p >= 1000 }.toList
for (chunk in Lst.chunks(bigPals, 10)) Fmt.print("$,6d", chunk)
System.print("\n%(bigPals.count) such primes found, %(pals.count) in all.")
Output:
Palindromic primes under 1,000:
  2   3   5   7  11 101 131 151 181 191
313 353 373 383 727 757 787 797 919 929

20 such primes found.

Additional palindromic primes under 100,000:
10,301 10,501 10,601 11,311 11,411 12,421 12,721 12,821 13,331 13,831
13,931 14,341 14,741 15,451 15,551 16,061 16,361 16,561 16,661 17,471
17,971 18,181 18,481 19,391 19,891 19,991 30,103 30,203 30,403 30,703
30,803 31,013 31,513 32,323 32,423 33,533 34,543 34,843 35,053 35,153
35,353 35,753 36,263 36,563 37,273 37,573 38,083 38,183 38,783 39,293
70,207 70,507 70,607 71,317 71,917 72,227 72,727 73,037 73,237 73,637
74,047 74,747 75,557 76,367 76,667 77,377 77,477 77,977 78,487 78,787
78,887 79,397 79,697 79,997 90,709 91,019 93,139 93,239 93,739 94,049
94,349 94,649 94,849 94,949 95,959 96,269 96,469 96,769 97,379 97,579
97,879 98,389 98,689

93 such primes found, 113 in all.