Prime numbers which contain 123: Difference between revisions

m
m (→‎{{header|Julia}}: add stretch)
m (→‎{{header|Wren}}: Minor tidy)
 
(32 intermediate revisions by 26 users not shown)
Line 8:
As above, but only show the <u>count</u> of those primes &nbsp; '''n''' &nbsp; that contain the (above) string, &nbsp; where &nbsp; '''n &nbsp; &lt; &nbsp; 1,000,000'''.
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="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 is_prime123(n)
R ‘123’ C String(n) & is_prime(n)
 
V c = 0
L(n) 100'000
I is_prime123(n)
c++
print(‘#5’.format(n), end' I c % 8 == 0 {"\n"} E ‘ ’)
print()
print(‘Found ’c‘ "123" primes less than 100000’)
c = 0
L(n) 1'000'000
I is_prime123(n)
c++
print()
print(‘Found ’c‘ "123" primes less than 1000000’)</syntaxhighlight>
 
{{out}}
<pre>
1123 1231 1237 8123 11239 12301 12323 12329
12343 12347 12373 12377 12379 12391 17123 20123
22123 28123 29123 31123 31231 31237 34123 37123
40123 41231 41233 44123 47123 49123 50123 51239
56123 59123 61231 64123 65123 70123 71233 71237
76123 81233 81239 89123 91237 98123
Found 46 "123" primes less than 100000
 
Found 451 "123" primes less than 1000000
</pre>
 
=={{header|ALGOL 68}}==
{{libheader|ALGOL 68-primes}}
<lang algol68>BEGIN # find primes whose decimal representation contains 123 #
<syntaxhighlight lang="algol68">BEGIN # find primes whose decimal representation contains 123 #
INT max prime = 1 000 000;
# sieve the primes to max prime #
PR read "primes.incl.a68" PR
[ 1 : max prime ]BOOL prime;
prime[ 1 ] := FALSE;BOOL prime[ 2= ]PRIMESIEVE :=max TRUEprime;
FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := TRUE OD;
FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := FALSE OD;
FOR i FROM 3 BY 2 TO ENTIER sqrt( UPB prime ) DO
IF prime[ i ] THEN FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := FALSE OD FI
OD;
# find the appropriate primes #
# as observed by the Wren sample, the primes must have a least 4 digits #
Line 46 ⟶ 83:
OD;
print( ( newline, "Found ", whole( p123 count, 0 ), " ""123"" primes below ", whole( UPB prime, 0 ), newline ) )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 56 ⟶ 93:
 
Found 451 "123" primes below 1000000
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">upTo100K: select select 2..99999 => odd? => prime?
upTo1M: upTo100K ++ select select 100001..999999 => odd? => prime?
 
contains123?: function [x] -> contains? to :string x "123"
 
loop split.every:10 select upTo100K => contains123? 'a ->
print map a => [pad to :string & 5]
 
print ""
print ["'123' Numbers < 1000000:" size select upTo1M => contains123?]</syntaxhighlight>
 
{{out}}
 
<pre> 1123 1231 1237 8123 11239 12301 12323 12329 12343 12347
12373 12377 12379 12391 17123 20123 22123 28123 29123 31123
31231 31237 34123 37123 40123 41231 41233 44123 47123 49123
50123 51239 56123 59123 61231 64123 65123 70123 71233 71237
76123 81233 81239 89123 91237 98123
 
'123' Numbers < 1000000: 451</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f PRIME_NUMBERS_WHICH_CONTAIN_123.AWK
BEGIN {
start = 1
stop = 99999
for (i=start; i<=stop; i++) {
if (is_prime(i) && i ~ /123/) {
printf("%6d%1s",i,++count%10?"":"\n")
}
}
printf("\nPrimes with '123' %d-%d: %d\n",start,stop,count)
stop = 999999
for (i=100000; i<=stop; i++) {
if (is_prime(i) && i ~ /123/) {
count++
}
}
printf("\nPrimes with '123' %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)
}
</syntaxhighlight>
{{out}}
<pre>
1123 1231 1237 8123 11239 12301 12323 12329 12343 12347
12373 12377 12379 12391 17123 20123 22123 28123 29123 31123
31231 31237 34123 37123 40123 41231 41233 44123 47123 49123
50123 51239 56123 59123 61231 64123 65123 70123 71233 71237
76123 81233 81239 89123 91237 98123
Primes with '123' 1-99999: 46
 
Primes with '123' 1-999999: 451
</pre>
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">global columna
print "Prime numbers which contain 123"
print
limite = 100000
call prime(limite, true)
print : print
print "Found "; columna; " prime numbers below "; limite
limite = 1e6
call prime(limite, false)
print : print
print "Found "; columna; " prime numbers below "; int(limite)
end
 
function isPrime(v)
if v < 2 then return False
if v mod 2 = 0 then return v = 2
if v mod 3 = 0 then return v = 3
d = 5
while d * d <= v
if v mod d = 0 then return False else d += 2
end while
return True
end function
 
subroutine prime(limite, mostrar)
columna = 0
 
for n = 1 to limite
strn$ = string(n)
if isPrime(n) and instr(strn$, "123") > 0 then
columna += 1
if mostrar then
print rjust(string(n), 7);
if columna mod 8 = 0 then print
end if
endif
next n
end subroutine</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="c++">
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
 
bool isPrime( int number ) {
if ( number < 2 ) {
return false ;
}
int stop = std::sqrt( static_cast<double>( number ) ) ;
for ( int i = 2 ; i <= stop ; ++i )
if ( number % i == 0 )
return false ;
return true ;
}
 
bool condition( int n ) {
std::string numberstring { std::to_string( n ) } ;
return isPrime( n ) && numberstring.find( "123" ) != std::string::npos ;
}
 
int main( ) {
std::vector<int> wantedPrimes ;
for ( int i = 1 ; i < 100000 ; i++ ) {
if ( condition( i ) )
wantedPrimes.push_back( i ) ;
}
int count = 0 ;
for ( int i : wantedPrimes ) {
std::cout << i << ' ' ;
count++ ;
if ( count % 10 == 0 ) {
std::cout << std::endl ;
}
}
count = wantedPrimes.size( ) ;
for ( int i = wantedPrimes.back( ) + 1 ; i < 1000000 ; i++ ) {
if ( condition ( i ) )
count++ ;
}
std::cout << std::endl ;
std::cout << "There are " << count << " such numbers below 1000000!\n" ;
return 0 ;
}</syntaxhighlight>
{{out}}
<pre>
1123 1231 1237 8123 11239 12301 12323 12329 12343 12347
12373 12377 12379 12391 17123 20123 22123 28123 29123 31123
31231 31237 34123 37123 40123 41231 41233 44123 47123 49123
50123 51239 56123 59123 61231 64123 65123 70123 71233 71237
76123 81233 81239 89123 91237 98123
There are 451 such numbers below 1000000!
</pre>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(ns primes-found-app
(:require [clojure.string :as str])
(:gen-class))
 
(defn is-prime? [n]
(if (< 1 n)
(empty? (filter #(= 0 (mod n %)) (range 2 n)))
false))
 
(defn get-prime-numbers [n]
(filter is-prime? (take n (range))))
 
(defn numbers-to-str [xs]
(map #(str %) xs))
 
(defn is-includes-123? [s]
(str/includes? s "123"))
 
(defn solution [number]
(->>
(get-prime-numbers number)
(numbers-to-str)
(filter is-includes-123?)))
 
(defn main []
(let [result (count (solution 1000000))]
(prn (solution 100000))
(format "There are %d primes that contain '123' below 1000000." result)
))
 
(main)
 
</syntaxhighlight>
{{out}}
<pre>
("1123" "1231" "1237" "8123" "11239" "12301" "12323" "12329" "12343" "12347" "12373" "12377" "12379" "12391" "17123" "20123" "22123" "28123" "29123" "31123" "31231" "31237" "34123" "37123" "40123" "41231" "41233" "44123" "47123" "49123" "50123" "51239" "56123" "59123" "61231" "64123" "65123" "70123" "71233" "71237" "76123" "81233" "81239" "89123" "91237" "98123")
"There are 451 primes that contain '123' below 1000000."
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">isqrt = proc (s: int) returns (int)
x0: int := s/2
if x0=0 then return(s) end
x1: int := (x0 + s/x0)/2
while x1 < x0 do
x0 := x1
x1 := (x0 + s/x0)/2
end
return(x0)
end isqrt
 
sieve = proc (n: int) returns (array[bool])
prime: array[bool] := array[bool]$fill(2,n-1,true)
for p: int in int$from_to(2,isqrt(n)) do
if prime[p] then
for c: int in int$from_to_by(p*p,n,p) do
prime[c] := false
end
end
end
return(prime)
end sieve
 
start_up = proc ()
po: stream := stream$primary_output()
count: int := 0
prime: array[bool] := sieve(1000000)
for p: int in array[bool]$indexes(prime) do
if ~prime[p] then continue end
if string$indexs("123", int$unparse(p))=0 then continue end
count := count + 1
if p < 100000 then
stream$putright(po, int$unparse(p), 7)
if count//10=0 then stream$putl(po, "") end
end
end
stream$putl(po, "\nThere are " || int$unparse(count)
|| " primes that contain '123' below 1,000,000.")
end start_up</syntaxhighlight>
{{out}}
<pre> 1123 1231 1237 8123 11239 12301 12323 12329 12343 12347
12373 12377 12379 12391 17123 20123 22123 28123 29123 31123
31231 31237 34123 37123 40123 41231 41233 44123 47123 49123
50123 51239 56123 59123 61231 64123 65123 70123 71233 71237
76123 81233 81239 89123 91237 98123
There are 451 primes that contain '123' below 1,000,000.</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
procedure ShowPrimesWith123(Memo: TMemo);
var N,Sum,Cnt1,Cnt2: integer;
var NS,S: string;
begin
Cnt1:=0;
Cnt2:=0;
Sum:=0;
for N:=123 to 1000000-1 do
if IsPrime(N) then
begin
NS:=IntToStr(N);
if Pos('123',NS)>0 then
begin
Inc(Cnt1);
if N<100000 then
begin
Inc(Cnt2);
S:=S+Format('%6d',[N]);
If (Cnt2 mod 8)=0 then S:=S+CRLF;
end;
end;
end;
Memo.Lines.Add(S);
Memo.Lines.Add('Count < 100,000 = '+IntToStr(Cnt2));
Memo.Lines.Add('Count < 1,000,000 = '+IntToStr(Cnt1));
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
1123 1231 1237 8123 11239 12301 12323 12329
12343 12347 12373 12377 12379 12391 17123 20123
22123 28123 29123 31123 31231 31237 34123 37123
40123 41231 41233 44123 47123 49123 50123 51239
56123 59123 61231 64123 65123 70123 71233 71237
76123 81233 81239 89123 91237 98123
Count < 100,000 = 46
Count < 1,000,000 = 451
Elapsed Time: 147.996 ms.
 
</pre>
 
 
=={{header|F_Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)].
<syntaxhighlight lang="fsharp">
// Numbers containing 123. Nigel Galloway: July 14th., 2021
let rec fN g=if g%1000=123 then true else if g<1230 then false else fN(g/10)
primes32()|>Seq.takeWhile((>)100000)|>Seq.filter fN|>Seq.iter(printf "%d "); printfn ""
printfn "Count to 1 million is %d" (primes32()|>Seq.takeWhile((>)1000000)|>Seq.filter fN|>Seq.length)
</syntaxhighlight>
{{out}}
<pre>
1123 1231 1237 8123 11239 12301 12323 12329 12343 12347 12373 12377 12379 12391 17123 20123 22123 28123 29123 31123 31231 31237 34123 37123 40123 41231 41233 44123 47123 49123 50123 51239 56123 59123 61231 64123 65123 70123 71233 71237 76123 81233 81239 89123 91237 98123
Count to 1 million is 451
</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2021-06-02}}
<langsyntaxhighlight lang="factor">USING: assocs formatting grouping io kernel literals math
math.functions math.functions.integer-logs math.primes
math.statistics sequences sequences.extras sequences.product
Line 95 ⟶ 454:
unzip cum-sum [ commas ] map swap zip
[ "Found %7s such primes under %s.\n" printf ] assoc-each
] time</langsyntaxhighlight>
{{out}}
<pre>
Line 115 ⟶ 474:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
Dim Shared As Integer column
 
Line 149 ⟶ 508:
Print !"\n\n\Encontrados "; column; " n£meros primos por debajo de"; limite
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 165 ⟶ 524:
 
Encontrados 451 números primos por debajo de 1000000
</pre>
 
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn IsPrime( n as long ) as BOOL
long i
BOOL result = YES
if ( n < 2 ) then result = NO : exit fn
for i = 2 to n + 1
if ( i * i <= n ) and ( n mod i == 0 )
result = NO : exit fn
end if
next
end fn = result
 
 
local fn PrimeWith123( limit as long )
long i, column = 1
CFStringRef numStr
NSLog( @"Prime numbers less than 100,000 which contain '123':\n" )
for i = 1 to limit
numStr = fn StringWithFormat( @"%lu", i )
if ( fn IsPrime( i ) ) and ( fn StringContainsString( numStr, @"123" ) )
NSLog( @"%-6lu\b", i )
if column == 10 then column = 0 : NSLog( @"" )
column++
end if
next
end fn
 
fn PrimeWith123( 100000 )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Prime numbers less than 100,000 which contain '123':
 
12373 12377 12379 12391 17123 20123 22123 28123 29123 31123
31231 31237 34123 37123 40123 41231 41233 44123 47123 49123
50123 51239 56123 59123 61231 64123 65123 70123 71233 71237
76123 81233 81239 89123 91237 98123
</pre>
 
Line 171 ⟶ 578:
{{trans|Wren}}
{{libheader|Go-rcu}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 215 ⟶ 622:
}
fmt.Println("\nFound", count, "such primes under", climit, "\b.")
}</langsyntaxhighlight>
 
{{out}}
Line 229 ⟶ 636:
 
Found 451 such primes under 1,000,000.
</pre>
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
import Data.List ( isInfixOf )
 
isPrime :: Int -> Bool
isPrime n
|n < 2 = False
|otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root]
where
root :: Int
root = floor $ sqrt $ fromIntegral n
condition :: Int -> Bool
condition n = isPrime n && isInfixOf "123" ( show n )
 
solution :: [Int]
solution = filter condition [2..99999]</syntaxhighlight>
{{out}}
<pre>
[1123,1231,1237,8123,11239,12301,12323,12329,12343,12347,12373,12377,12379,12391,17123,20123,22123,28123,29123,31123,31231,31237,34123,37123,40123,41231,41233,44123,47123,49123,50123,51239,56123,59123,61231,64123,65123,70123,71233,71237,76123,81233,81239,89123,91237,98123]
</pre>
 
=={{header|J}}==
<syntaxhighlight lang="j"> p:I.1 2 3 +./@E."1/ 10 #.inv p:i.p:inv 1e5 NB. primes less than 1e5 containing decimal digit sequence 1 2 3
1123 1231 1237 8123 11239 12301 12323 12329 12343 12347 12373 12377 12379 12391 17123 20123 22123 28123 29123 31123 31231 31237 34123 37123 40123 41231 41233 44123 47123 49123 50123 51239 56123 59123 61231 64123 65123 70123 71233 71237 76123 81233 81239 89123 91237 98123
+/1 2 3 +./@E."1/ 10 #.inv p:i.p:inv 1e6 NB. count of primes less than 1e6 containing decimal digit sequence 1 2 3
451</syntaxhighlight>
 
<code>p:inv 1e5</code> is 9592 -- the number of primes less than 1e5. <code>p:i.9592</code> enumerates those primes (first is 2, last is 99991). <code>10 #.inv</code> converts this to the corresponding table of decimal digits (<code>0 0 0 0 2</code> for the first row, <code>9 9 9 9 1</code> for the last row). <code>1 2 3 +./@E."1 </code> identifies those rows containing the sequence <code>1 2 3</code>, and <code>I.</code> gets the indices of those rows and, finally, <code>p:</code> gets the prime numbers corresponding to those indices. Similarly, <code>+/</code> counts the rows with suitable primes.
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
For a suitable implementation of `is_prime`, see e.g. # [[Erd%C5%91s-primes#jq]].
<syntaxhighlight lang="jq">def count(stream): reduce stream as $i (0; .+1);
 
def digits: tostring | explode;
 
# Input: an upper bound, or `infinite`
def primes_with_123:
("123"| digits) as $d123
| range(123; .; 2))
| select( (digits | index($d123)) and is_prime);
 
100000 | primes_with_123,
 
(1000000
| "\nThere are \(count(primes_with_123)) \"123\" primes less than \(.).")</syntaxhighlight>
{{out}}
(Abbreviated)
<pre>
1123
1231
1237
8123
...
81233
81239
89123
91237
98123
 
There are 451 "123" primes less than 1000000.
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Primes
 
function containstringinbase(N, str, base, verbose = true)
arr = filter(n -> occursin(str, string(n, base=base)), primes(N))
printprintln("\n\nFound $(length(arr)) primes < $N which contain the string $str in base $base representation.")
verbose && foreach(p -> print(rpad(p[2], 6), p[1] % 12 == 0 ? "\n" : ""), enumerate(arr))
end
Line 243 ⟶ 716:
containstringinbase(1_000_000, "123", 10, false)
containstringinbase(1_000_000_000, "123", 10, false)
</langsyntaxhighlight>{{out}}
<pre>
Found 46 primes < 100000 which contain the string 123 in base 10 representation.1123 1231 1237 8123 11239 12301 12323 12329 12343 12347 12373 12377
1123 1231 1237 8123 11239 12301 12323 12329 12343 12347 12373 12377
12379 12391 17123 20123 22123 28123 29123 31123 31231 31237 34123 37123
40123 41231 41233 44123 47123 49123 50123 51239 56123 59123 61231 64123
Line 251 ⟶ 725:
 
Found 451 primes < 1000000 which contain the string 123 in base 10 representation.
 
 
Found 435002 primes < 1000000000 which contain the string 123 in base 10 representation.
</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Prime numbers which contain 123
 
# # Variables:
#
integer MAX_SHOW=100000 MAX_COUNT=1000000 primecnt=0
pattrn='123'
typeset -a parr
 
# # Functions:
#
 
# # Function _isprime(n) return 1 for prime, 0 for not prime
#
function _isprime {
typeset _n ; integer _n=$1
typeset _i ; integer _i
 
(( _n < 2 )) && return 0
for (( _i=2 ; _i*_i<=_n ; _i++ )); do
(( ! ( _n % _i ) )) && return 0
done
return 1
}
 
 
######
# main #
######
 
for ((i=2; i<MAX_COUNT; i++)); do
_isprime ${i}
if (( $? )); then
if [[ ${i} == *${pattrn}* ]]; then
((primecnt++))
(( i < MAX_SHOW )) && parr+=( ${i} )
fi
fi
done
 
print ${parr[*]}
print ${#parr[*]} found under $MAX_SHOW
echo ; print ${primecnt} found under $MAX_COUNT</syntaxhighlight>
{{out}}<pre>1123 1231 1237 8123 11239 12301 12323 12329 12343 12347 12373 12377 12379
12391 17123 20123 22123 28123 29123 31123 31231 31237 34123 37123 40123 41231 41233 44123 47123
49123 50123 51239 56123 59123 61231 64123 65123 70123 71233 71237 76123 81233 81239 89123 91237 98123
46 found under 100000
 
451 found under 1000000</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">s1 = Select[Prime[Range[PrimePi[10^5]]], IntegerDigits/*(SequenceCount[#, {1, 2, 3}] &)/*GreaterThan[0]]
Length[s1]
 
Length[Select[Prime[Range[PrimePi[10^6]]], IntegerDigits/*(SequenceCount[#, {1, 2, 3}] &)/*GreaterThan[0]]]</syntaxhighlight>
{{out}}
<pre>{1123, 1231, 1237, 8123, 11239, 12301, 12323, 12329, 12343, 12347, 12373, 12377, 12379, 12391, 17123, 20123, 22123, 28123, 29123, 31123, 31231, 31237, 34123, 37123, 40123, 41231, 41233, 44123, 47123, 49123, 50123, 51239, 56123, 59123, 61231, 64123, 65123, 70123, 71233, 71237, 76123, 81233, 81239, 89123, 91237, 98123}
46
451</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import sequtils, strutils
 
const N = 1_000_000 - 1 # Sieve of Erathostenes size.
Line 289 ⟶ 827:
var count = 0
for _ in primes123(1_000_000): inc count
echo "Found ", count, " “123” primes less than 1_000_000."</langsyntaxhighlight>
 
{{out}}
Line 302 ⟶ 840:
Found 451 “123” primes less than 1_000_000.</pre>
 
=={{header|Perl}}==
{{libheader|ntheory}}
<syntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict;
use warnings;
use ntheory qw( primes );
 
my @hundredthousand = grep /123/, @{ primes(1e5) };
my $million = grep /123/, @{ primes(1e6) };
print "@hundredthousand\n\nmillion count is $million\n" =~ s/.{70}\K /\n/gr;</syntaxhighlight>
{{out}}
<pre>
1123 1231 1237 8123 11239 12301 12323 12329 12343 12347 12373 12377 12379
12391 17123 20123 22123 28123 29123 31123 31231 31237 34123 37123 40123
41231 41233 44123 47123 49123 50123 51239 56123 59123 61231 64123 65123
70123 71233 71237 76123 81233 81239 89123 91237 98123
 
million count is 451
</pre>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">csm123</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #000000008000;">s"123"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ns</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;">fn</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;">filter</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_primes_le</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">),</span><span style="color: #000000;">cs</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"123"m123</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: #000000;">fn</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100_000</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;">"found %d &lt; 100_000: %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</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">))})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"found %d &lt; 1_000_000\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1_000_000</span><span style="color: #0000FF;">))})</span>
<!--</syntaxhighlight>-->
<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;">"found %d &lt; 1_000_000\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>
<!--</lang>-->
{{out}}
<pre>
Line 318 ⟶ 875:
found 451 < 1_000_000
</pre>
 
=={{header|PureBasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="purebasic">Procedure isPrime(v.i)
If v <= 1 : ProcedureReturn #False
ElseIf v < 4 : ProcedureReturn #True
ElseIf v % 2 = 0 : ProcedureReturn #False
ElseIf v < 9 : ProcedureReturn #True
ElseIf v % 3 = 0 : ProcedureReturn #False
Else
Protected r = Round(Sqr(v), #PB_Round_Down)
Protected f = 5
While f <= r
If v % f = 0 Or v % (f + 2) = 0
ProcedureReturn #False
EndIf
f + 6
Wend
EndIf
ProcedureReturn #True
EndProcedure
 
Global column.i
 
Procedure prime(limite.l, mostrar.b)
column = 0
For n = 1 To limite
strn.s = Str(n)
If isPrime(n) And FindString(strn,"123") > 0:
column + 1
If mostrar:
Print(FormatNumber(n,0,"","") + " ")
If column % 8 = 0: PrintN("") : EndIf
EndIf
EndIf
Next n
EndProcedure
 
OpenConsole()
PrintN("Prime numbers which contain 123")
limite.l = 1e5
prime(limite, #True)
PrintN(#CRLF$ + #CRLF$ + "Found " + Str(column) + " prime numbers below " + Str(limite))
limite = 1e6
prime(limite, #False)
PrintN(#CRLF$ + "Found " + Str(column) + " prime numbers below " + Str(limite))
Input()
CloseConsole()</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|Python}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="python">
#!/usr/bin/python
 
Line 347 ⟶ 955:
prime(limite, False)
print("\n\nEncontrados ", columna, " números primos por debajo de", limite)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
 
=={{header|Quackery}}==
 
<code>eratosthenes</code> and <code>isprime</code> are defined at [[Sieve of Eratosthenes#Quackery]].
 
<syntaxhighlight lang="Quackery"> 100000 eratosthenes
 
[ false swap
[ dup 122 > while
dup 1000 mod
123 = iff
[ dip not ]
done
10 / again ]
drop ] is contains123 ( n --> b )
 
[]
100000 times
[ i^ isprime if
[ i^ contains123 if
[ i^ join ] ] ]
[] swap witheach
[ number$ nested join ]
48 wrap$</syntaxhighlight>
 
{{out}}
 
<pre>1123 1231 1237 8123 11239 12301 12323 12329
12343 12347 12373 12377 12379 12391 17123 20123
22123 28123 29123 31123 31231 31237 34123 37123
40123 41231 41233 44123 47123 49123 50123 51239
56123 59123 61231 64123 65123 70123 71233 71237
76123 81233 81239 89123 91237 98123</pre>
 
 
=={{header|Raku}}==
<syntaxhighlight lang="raku" perl6line>my @p123 = ^∞ .grep: { (.is-primecontains: 123) && .contains: 123is-prime };
 
put display @p123[^(@p123.first: * > 1e5, :k)];
Line 363 ⟶ 1,005:
cache $list;
$title ~ $list.batch($cols)».fmt($fmt).join: "\n"
}</langsyntaxhighlight>
{{out}}
<pre>46 matching:
Line 379 ⟶ 1,021:
<br>the number of columns to be shown, &nbsp; and the decimal string that the primes must contain. &nbsp; A negative number for
<br>the number of columns suppresses the list of primes, &nbsp; but shows the total number of primes found.
<langsyntaxhighlight lang="rexx">/*REXX program finds & displays primes (in decimal) that contain the decimal digits 123.*/
parse arg hi cols str . /*obtain optional argument from the CL.*/
if hi=='' | hi=="," then hi= 100000 /*Not specified? Then use the default.*/
Line 412 ⟶ 1,054:
/*──────────────────────────────────────────────────────────────────────────────────────*/
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 /* " " " #=5; " sq.#= @.# **2 semaphores./*number of primes so far; prime square*/
#=5; sq.#= @.# **2 /*number of primes so far; prime². */
do j=@.#+2 by 2 to hi-1 /*find odd primes from here on. */
parse var j '' -1 _; if _==5 then iterate /*J divisible by 5? (right dig)*/
Line 421 ⟶ 1,062:
if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */
end /*k*/ /* [↑] only process numbers ≤ √ J */
#= #+1; @.#= j; sq.#= j*j; !.j= 1 /*bump # of Ps; assign next P; P²; P# square*/
end /*j*/; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 443 ⟶ 1,084:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
row = 0
Line 464 ⟶ 1,105:
see nl + "Found " + row + " numbers" + nl
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 481 ⟶ 1,122:
Found 46 numbers
done...
</pre>
 
=={{header|RPL}}==
===Brute force===
≪ ALOG → max
≪ { } 1123
'''WHILE''' DUP max < '''REPEAT'''
NEXTPRIME
'''IF''' DUP →STR "123" POS '''THEN''' SWAP OVER + SWAP '''END'''
'''END''' NIP
≫ ≫ '<span style="color:blue">TASK</span>’ STO
{{out}}
<pre>
1: { 1123 1231 1237 8123 11239 12301 12323 12329 12343 12347 12373 12377 12379 12391 17123 20123 22123 28123 29123 31123 31231 31237 34123 37123 40123 41231 41233 44123 47123 49123 50123 51239 56123 59123 61231 64123 65123 70123 71233 71237 76123 81233 81239 89123 91237 98123 }
</pre>
Runs in 12 minutes 45 seconds on a HP-50g
 
===Lexicographic approach===
 
{| class="wikitable"
! RPL code
! Comment
|-
|
3 - DUP ALOG 1 - { } → ndigits maxleft results
≪ 0
'''DO'''
DUP DUP "" IFTE
ndigits OVER SIZE - ALOG 1 +
DUP 2 x 3 - '''FOR''' j
DUP "123" + j →STR TAIL + STR→
'''IF''' DUP ISPRIME? '''THEN''' 'results' STO+ '''ELSE''' DROP '''END'''
2 '''STEP'''
DROP 1 +
'''UNTIL''' DUP maxleft > '''END'''
DROP results
≫ ≫ '<span style="color:blue">PR123N</span>’ STO
|
<span style="color:blue">PR123N</span> ''( n_digits → { primes_with_123 } ) ''
n_digits -= 3 ; maxleft = 10^n_digits - 1
leftval = 0
loop
left = leftval == 0 ? "" ; leftval
tmp = 10^(n_digits - length(leftval)) + 1
for j = tmp to (tmp*2 - 3) step 2
n = left + "123" + j[2..]
add n to results if prime
next j
leftval++
end loop
display results (unsorted)
|}
4 <span style="color:blue">PR123N</span> 5 <span style="color:blue">PR123N</span> + SORT
Runs in 22 seconds on a HP-50g (35 times faster than brute force) - same results as above.
Finding the 451 primes under one million takes 4 minutes 30 seconds.
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">require 'prime'
 
RE = /123/
puts Prime.each(100_000).select {|prime| RE.match? prime.to_s}.join(" "), ""
puts "#{Prime.each(1_000_000).count {|prime| RE.match? prime.to_s} } 123-primes below 1 million."
</syntaxhighlight>
{{out}}
<pre>1123 1231 1237 8123 11239 12301 12323 12329 12343 12347 12373 12377 12379 12391 17123 20123 22123 28123 29123 31123 31231 31237 34123 37123 40123 41231 41233 44123 47123 49123 50123 51239 56123 59123 61231 64123 65123 70123 71233 71237 76123 81233 81239 89123 91237 98123
 
451 123-primes below 1 million.
</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func numbers_with_subdigits(upto, base = 10, s = 123.digits(base)) {
Enumerator({|callback|
for k in (0 .. base**(upto.len(base) - s.len)) {
 
var d = k.digits(base)
 
for i in (0 .. d.len) {
var n = d.clone.insert(i, s...).digits2num(base)
callback(n) if (n <= upto)
}
 
var z = d.clone.insert(d.len, s...)
loop {
var n = z.insert(d.len, 0).digits2num(base)
(n <= upto) ? callback(n) : break
}
}
})
}
 
say "Decimal primes under 100,000 which contain '123':"
numbers_with_subdigits(1e5).grep { .is_prime }.sort.each_slice(10, {|*a|
say a.map { '%6s' % _ }.join(' ')
})
 
say ''
 
for n in (4..8) {
var count = numbers_with_subdigits(10**n).grep { .is_prime }.len
say "Found #{'%6s' % count.commify} such primes < 10^#{n}"
}</syntaxhighlight>
{{out}}
<pre>
Decimal primes under 100,000 which contain '123':
1123 1231 1237 8123 11239 12301 12323 12329 12343 12347
12373 12377 12379 12391 17123 20123 22123 28123 29123 31123
31231 31237 34123 37123 40123 41231 41233 44123 47123 49123
50123 51239 56123 59123 61231 64123 65123 70123 71233 71237
76123 81233 81239 89123 91237 98123
 
Found 4 such primes < 10^4
Found 46 such primes < 10^5
Found 451 such primes < 10^6
Found 4,412 such primes < 10^7
Found 43,548 such primes < 10^8
</pre>
 
Line 486 ⟶ 1,244:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
{{libheader|Wren-seq}}
The only number under 1,000 which can possibly satisfy the task description is 123 and that's clearly divisible by 3 and hence composite.
<langsyntaxhighlight ecmascriptlang="wren">import "./math" for Int
import "./fmt" for Fmt
import "/seq" for Lst
 
var limit = 1e5
Line 496 ⟶ 1,252:
var results = primes.where { |p| p < limit && p.toString.contains("123") }.toList
Fmt.print("Primes under $,d which contain '123' when expressed in decimal:", limit)
Fmt.tprint("$,7d", results, 10)
for (chunk in Lst.chunks(results, 10)) Fmt.print("$,7d", chunk)
Fmt.print("\nFound $,d such primes under $,d.", results.count, limit)
 
limit = 1e6
var count = primes.count { |p| p.toString.contains("123") }
Fmt.print("\nFound $,d such primes under $,d.", count, limit)</langsyntaxhighlight>
 
{{out}}
Line 515 ⟶ 1,271:
 
Found 451 such primes under 1,000,000.
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func IsPrime(N); \Return 'true' if N is a prime number
int N, I;
[if N <= 1 then return false;
for I:= 2 to sqrt(N) do
if rem(N/I) = 0 then return false;
return true;
];
 
func Has123(N); \Return 'true' if N contains sequential digits 1 2 3
int N, C, D;
[C:= 3;
repeat N:= N/10;
D:= rem(0);
if D = C then
[C:= C-1;
if C = 0 then return true;
]
else [C:= 3;
if D = C then C:= 2;
];
until N=0;
return false;
];
 
int N, Count;
[Count:= 0;
for N:= 123 to 1_000_000-1 do
[if Has123(N) then if IsPrime(N) then
[Count:= Count+1;
if N < 100_000 then
[IntOut(0, N);
if rem(Count/10) = 0 then CrLf(0) else ChOut(0, 9\tab\);
];
];
if N = 100_000 then
[CrLf(0); IntOut(0, Count); Text(0, " ^"123^" primes found below 100,000.")];
];
CrLf(0); IntOut(0, Count); Text(0, " ^"123^" primes found below 1,000,000.");
]</syntaxhighlight>
 
{{out}}
<pre>
1123 1231 1237 8123 11239 12301 12323 12329 12343 12347
12373 12377 12379 12391 17123 20123 22123 28123 29123 31123
31231 31237 34123 37123 40123 41231 41233 44123 47123 49123
50123 51239 56123 59123 61231 64123 65123 70123 71233 71237
76123 81233 81239 89123 91237 98123
46 "123" primes found below 100,000.
451 "123" primes found below 1,000,000.
</pre>
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="yabasic">
sub isPrime(v)
if v < 2 then return False : fi
Line 556 ⟶ 1,364:
print "\n\nEncontrados ", columna, " n£meros primos por debajo de ", limite
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
9,476

edits