Jump to content

Palindromic primes: Difference between revisions

→‎{{header|jq}}: (corrected)
(→‎{{header|jq}}: (corrected))
Line 280:
919
929</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
In this entry, we define both a naive generate-and-test generator of the palindromic primes,
and a more sophisticated one that is well-suited for generating very large numbers of such primes,
as illustrated by counting the number less than 10^9.
 
For a suitable implementation of `is_prime` as used here, see [[Erd%C5%91s-primes#jq]].
 
'''Preliminaries'''
<lang jq>def count(s): reduce s as $x (null; .+1);
 
def emit_until(cond; stream): label $out | stream | if cond then break $out else . end;</lang>
'''Naive version'''
<lang jq>
def primes:
2, (range(3;infinite;2) | select(is_prime));
 
def palindromic_primes_slowly:
primes | select( tostring|explode | (. == reverse));
</lang>
'''Less naive version'''
<lang jq># Output: an unbounded stream of palindromic primes
def palindromic_primes:
 
# Output: a naively constructed stream of palindromic strings of length >= 2
def palindromic_candidates:
def rev: # reverse a string
explode|reverse|implode;
def unconstrained($length):
if $length==1 then range(0;10) | tostring
else (range(0;10)|tostring)
| . + unconstrained($length -1 )
end;
def middle($length): # $length > 0
if $length==1 then range(0;10) | tostring
elif $length % 2 == 1
then (($length -1) / 2) as $len
| unconstrained($len) as $left
| (range(0;10) | tostring) as $mid
| $left + $mid + ($left|rev)
else ($length / 2) as $len
| unconstrained($len) as $left
| $left + ($left|rev)
end;
range(1;infinite) as $mid
| ("1", "3", "7", "9") as $start
| $start + middle($mid) + $start ;
2, 3, 5, 7, 11,
(palindromic_candidates | tonumber | select(is_prime));</lang>
'''Demonstrations'''
<lang jq>"Palindromic primes <= 1000:",
emit_until(. >= 1000; palindromic_primes),
 
((range(5;10) | pow(10;.)) as $n
| "\nNumber of palindromic primes <= \($n): \(count(emit_until(. >= $n; palindromic_primes)))" )</lang>
{{out}}
<pre>
Palindromic primes <= 1000:
2
3
5
7
11
101
131
151
181
191
313
353
373
383
727
757
787
797
919
929
 
Number of palindromic primes <= 100000: 113
 
Number of palindromic primes <= 1000000: 113
 
Number of palindromic primes <= 10000000: 781
 
Number of palindromic primes <= 100000000: 781
 
Number of palindromic primes <= 1000000000: 5953
</pre>
 
 
=={{header|Julia}}==
2,471

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.