Primes with digits in nondecreasing order
- Task
Find all primes (n) with their decimal digits in non-decreasing order, where n < 1,000
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_non_decreasing(=n)
V prev = 10
L n != 0
V d = n % 10
I d > prev {R 0B}
prev = d
n I/= 10
R 1B
V c = 0
L(n) 1000
I is_non_decreasing(n) & is_prime(n)
c++
print(‘#3’.format(n), end' I c % 10 == 0 {"\n"} E ‘ ’)
print()
print(‘Found ’c‘ primes with digits in nondecreasing order’)
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 Found 50 primes with digits in nondecreasing order
Action!
INCLUDE "H6:SIEVE.ACT"
BYTE FUNC NonDecreasingDigits(INT x)
BYTE c,d,last
c=0 last=9
WHILE x#0
DO
d=x MOD 10
IF d>last THEN
RETURN (0)
FI
last=d
x==/10
OD
RETURN (1)
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=2 TO MAX
DO
IF primes(i)=1 AND NonDecreasingDigits(i)=1 THEN
PrintI(i) Put(32)
count==+1
FI
OD
PrintF("%E%EThere are %I primes",count)
RETURN
- Output:
Screenshot from Atari 8-bit computer
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 There are 50 primes
ALGOL 68
BEGIN # find primes where the digits are non-descending #
INT max number = 1000;
# sieve the primes to max number #
PR read "primes.incl.a68" PR
[]BOOL prime = PRIMESIEVE max number;
# we can easily generate candidate numbers with a few nested loops #
INT p count := 0;
# apart from 1 digit primes, the final digit can only be 1, 3, 7 or 9 #
# however we don't optimise that here #
FOR h FROM 0 TO 9 DO
FOR i FROM h TO 9 DO
INT hi = ( h * 10 ) + i;
FOR j FROM i TO 9 DO
INT hij = ( 10 * hi ) + j;
FOR k FROM IF j = 0 THEN 1 ELSE j FI TO 9
WHILE INT hijk = ( hij * 10 ) + k;
hijk <= max number
DO
IF prime[ hijk ] THEN
p count +:= 1;
print( ( " ", whole( hijk, -6 ) ) );
IF p count MOD 12 = 0 THEN print( ( newline ) ) FI
FI
OD # k #
OD # j #
OD # i #
OD # h # ;
print( ( newline
, newline
, "Found "
, whole( p count, 0 )
, " non-descending primes up to "
, whole( max number, 0 )
, newline
)
)
END
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 Found 50 non-descending primes up to 1000
APL
(⊢(/⍨)(∧/2≤/10(⊥⍣¯1)⊢)¨)∘(⊢(/⍨)(2=0+.=⍳|⊢)¨)⍳1000
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
Arturo
primes: select 1..1000 => prime?
nondecreasing?: function [n][
ds: digits n
if 1 = size ds -> return true
lastDigit: first ds
loop 1..dec size ds 'i [
digit: ds\[i]
if digit < lastDigit -> return false
lastDigit: digit
]
return true
]
loop split.every: 10 select primes => nondecreasing? 'a ->
print map a => [pad to :string & 4]
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
AWK
# syntax: GAWK -f PRIMES_WITH_DIGITS_IN_NONDECREASING_ORDER.AWK
BEGIN {
start = 1
stop = 1000
for (i=start; i<=stop; i++) {
if (is_prime(i)) {
flag = 1
for (j=1; j<length(i); j++) {
if (substr(i,j,1) > substr(i,j+1,1)) {
flag = 0
}
}
if (flag == 1) {
printf("%4d%1s",i,++count%10?"":"\n")
}
}
}
printf("\nPrimes with digits in nondecreasing order %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)
}
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 Primes with digits in nondecreasing order 1-1000: 50
BASIC
10 DEFINT A-Z
20 DIM P(1000)
30 P(0)=-1: P(1)=-1
40 FOR I=2 TO SQR(1000)
50 IF P(I)=0 THEN FOR J=I+I TO 1000 STEP I: P(J)=-1: NEXT
60 NEXT
70 FOR A=0 TO 9: FOR B=A TO 9: FOR C=B TO 9
80 N=A*100+B*10+C
90 IF P(N)=0 THEN PRINT N,
100 NEXT C,B,A
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
BASIC256
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
function is_ndp(n)
d = 10
do
ld = d
d = n mod 10
if d > ld then return False
n /= 10
until n = 0
return True
end function
c = 0
print "Primes below 1,000 with digits in non-decreasing order:"
for i = 2 to 999
if isPrime(i) and is_ndp(i) then
c += 1
print i; chr(9);
if c mod 10 = 0 then print
end if
next i
print chr(10); c; " such primes found."
end
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
Procedure is_ndp(n.i)
d.i = 10
Repeat
ld.i = d
d = n % 10
If d > ld
ProcedureReturn #False
EndIf
n / 10
Until n = 0
ProcedureReturn #True
EndProcedure
OpenConsole()
c.i = 0
PrintN("Primes below 1,000 with digits in non-decreasing order:")
For i.i = 2 To 999
If isPrime(i) And is_ndp(i)
c + 1
Print(Str(i) + #TAB$)
If c % 10 = 0 : PrintN("") : EndIf
EndIf
Next i
PrintN(#CRLF$ + Str(c) + " such primes found."): Input()
CloseConsole()
Yabasic
sub isPrime(v)
if v < 2 then return False : fi
if mod(v, 2) = 0 then return v = 2 : fi
if mod(v, 3) = 0 then return v = 3 : fi
d = 5
while d * d <= v
if mod(v, d) = 0 then return False else d = d + 2 : fi
wend
return True
end sub
sub is_ndp(n)
d = 10
repeat
ld = d
d = mod(n, 10)
if d > ld then return False : fi
n = int(n / 10)
until n = 0
return True
end sub
c = 0
print "Primes below 1,000 with digits in non-decreasing order:"
for i = 2 to 999
if isPrime(i) and is_ndp(i) then
c = c + 1
print i using "####";
if mod(c, 10) = 0 then print : fi
endif
next i
print chr$(10), c, " such primes found."
end
BCPL
get "libhdr";
let sieve(prime, max) be
$( 0!prime := false
1!prime := false
for i=2 to max do i!prime := true
for i=2 to max/2
if i!prime
$( let j = i*2
while j <= max
$( j!prime := false
j := j + i
$)
$)
$)
let start() be
$( let prime = getvec(1000)
let c = 0
sieve(prime, 1000)
for d100 = 0 to 9
for d10 = d100 to 9
for d1 = d10 to 9
$( let n = d100*100 + d10*10 + d1
if n!prime then
$( writed(n,4)
c := c + 1
if c rem 10 = 0 then wrch('*N')
$)
$)
freevec(prime)
$)
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
C#
The chars array explicitly enforces the case order, not relying on the language's idea of what letters are before or after each other.
using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;
class Program {
static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
// convert an int into a string using the current ba
static string from10(int b) { string res = ""; int re; while (b > 0) {
b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }
// parse a string into an int, using current ba (not used here)
static int to10(string s) { int res = 0; foreach (char i in s)
res = res * ba + chars.IndexOf(i); return res; }
// note: comparing the index of the chars instead of the chars themsleves, which avoids case issues
static bool nd(string s) { if (s.Length < 2) return true;
char l = s[0]; for (int i = 1; i < s.Length; i++)
if (chars.IndexOf(l) > chars.IndexOf(s[i]))
return false; else l = s[i] ; return true; }
static void Main(string[] args) { int c, lim = 1000; string s;
foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {
ba = b; c = 0; foreach (var a in PG.Primes(lim))
if (nd(s = from10(a))) Write("{0,4} {1}", s, ++c % 20 == 0 ? "\n" : "");
WriteLine("\nBase {0}: found {1} non-decreasing primes under {2:n0}\n", b, c, from10(lim)); } } }
class PG { public static IEnumerable<int> Primes(int lim) {
var flags = new bool[lim + 1]; int j; yield return 2;
for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;
for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
if (!flags[j]) { yield return j;
for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }
for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
- Output:
11 111 11111 1111111 Base 2: found 4 non-decreasing primes under 1111101000 2 12 111 122 1112 1222 Base 3: found 6 non-decreasing primes under 1101001 2 3 11 13 23 113 133 223 233 1223 1333 2333 11123 11233 11333 12233 22223 Base 4: found 17 non-decreasing primes under 33220 2 3 12 23 34 111 122 133 1112 1123 1233 1244 2223 2344 3444 11122 12222 Base 5: found 17 non-decreasing primes under 13000 2 3 5 11 15 25 35 45 111 115 125 135 155 225 245 255 335 345 445 455 1115 1125 1145 1235 1245 1335 1345 1355 1445 1555 2225 2335 2345 2555 3445 3455 3555 Base 6: found 37 non-decreasing primes under 4344 2 3 5 14 16 23 25 56 113 115 124 133 146 155 166 245 256 335 344 346 445 566 1112 1123 1136 1156 1222 1226 1235 1345 1444 1466 2234 2236 2333 2335 2366 2555 Base 7: found 38 non-decreasing primes under 2626 2 3 5 7 13 15 23 27 35 37 45 57 111 117 123 145 147 155 177 225 227 235 247 255 277 337 345 357 445 467 557 577 667 1113 1127 1137 1145 1167 1223 1225 1245 1335 1347 1357 1467 1555 1567 Base 8: found 47 non-decreasing primes under 1750 2 3 5 7 12 14 18 25 34 45 47 58 67 78 117 122 124 128 135 155 177 234 238 267 278 337 344 355 377 447 557 568 667 678 788 1112 1114 1118 1147 1158 1178 1222 1255 1268 1288 Base 9: found 45 non-decreasing primes under 1331 2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 Base 10: found 50 non-decreasing primes under 1000 2 3 5 7 B D 11 13 17 1D 1F 25 29 2B 2F 35 3B 3D 47 49 4F 59 67 6B 6D 7F 89 8B 9D AD BF DF EF 115 119 11B 125 133 137 139 13D 14B 15B 15D 167 16F 17B 17F 18D 199 1AF 1BB 1CD 1CF 1DF 223 22D 233 239 23B 24B 257 259 25F 269 26B 277 28D 2AB 2BD 2CF 2DD 2EF 335 337 33B 33D 347 355 359 35B 35F 36D 377 38B 38F 3AD 3DF Base 16: found 88 non-decreasing primes under 3E8 2 3 5 7 B D 12 16 1C 1E 23 27 29 2D 38 3A 3G 45 4B 4F 5C 5G 67 6B 78 7C 8D 8F 9A 9E AB BC FG 111 115 117 11B 128 12E 137 139 13D 14A 14G 155 159 15F 166 16A 17B 17D 188 18E 19F 1BB 1BF 1CG 1DD 1EE 1GG 225 227 23C 23E 247 24D 24F 25A 25E 26B 27C 28D 29C 2AD 2CF 33B 346 34C 35F 368 36E 37B Base 17: found 82 non-decreasing primes under 37E 2 3 5 7 B D H J N 12 14 1A 1E 1G 1K 1Q 25 27 2D 2H 2J 2P 38 3G 3K 3M 3Q 45 4J 4N 5E 5G 5M 6B 6H 6J 78 7A 7M 8B 8D 8H 8N 8P 9E 9K 9Q AB AD AN BE BG BK CD CN CP DG DM EJ EN FG FQ GH GP HK IN KN LQ MN MP NQ OP PQ 111 115 11D 11H 124 12E 12Q 13B 13D 13H 13J 14G 14K 14M 14Q 15D 15H 15J 15N 16G 16K 17B 17J 17N 188 18M 18Q 19B 19J 19P Base 27: found 103 non-decreasing primes under 1A1 2 3 5 7 B D H J N T 16 1A 1C 1G 1M 1S 1U 25 29 2B 2H 2L 2R 34 38 3A 3E 3G 3K 47 4D 4F 4P 4R 58 5C 5I 5O 5Q 67 6B 6D 6P 7A 7C 7G 7M 7O 89 8F 8L 8N 8T 9E 9S AL AR BC BI BQ CH CP CT DG DI DS DU EF EN ER ET FM FQ GP GR HK HU IJ IT JO JS JU KL KN KR LM LQ MR NQ NU OP OT TU 115 Base 31: found 94 non-decreasing primes under 118 2 3 5 7 B D H J N T V b f h l r x z 15 19 1B 1H 1L 1R 1Z 1d 1f 1j 1l 1p 23 27 2D 2F 2P 2R 2X 2d 2h 2n 2t 2v 35 37 3B 3D 3P 3b 3f 3h 3l 3r 3t 49 4F 4L 4N 4T 4X 4Z 4j 4x 57 5L 5R 5b 5d 5h 5n 5v 67 6B 6H 6P 6T 6b 6l 6n 6x 6z 79 7F 7N 7R 7T 7X 7j 7r 7v 8D 8P 8R 8j 8p 8z 9B 9D 9J 9T 9Z 9f 9h 9n 9t 9x 9z AB AL AN AR AX Ad Af Ar Av BJ BR Bb Bj Bp Bv Bz CD CH CP CT Ch Cr DF DH DL DN DX Dl Dp Dr Dv EF EJ Ed Eh Ep Ez FH FN Fb Ff Fl Fr Fz Base 62: found 150 non-decreasing primes under G8
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;
procedure GetDigits(N: integer; var IA: TIntegerDynArray);
{Get an array of the integers in a number}
var T: integer;
begin
SetLength(IA,0);
repeat
begin
T:=N mod 10;
N:=N div 10;
SetLength(IA,Length(IA)+1);
IA[High(IA)]:=T;
end
until N<1;
end;
procedure NonDecreasingPrime(Memo: TMemo);
var I,Cnt: integer;
var IA: TIntegerDynArray;
var S: string;
function NotDecreasing(N: integer): boolean;
var I: integer;
begin
Result:=False;
GetDigits(N,IA);
for I:=0 to High(IA)-1 do
if IA[I]<IA[I+1] then exit;
Result:=True;
end;
begin
Cnt:=0;
S:='';
for I:=0 to 1000-1 do
if IsPrime(I) then
if NotDecreasing(I) then
begin
Inc(Cnt);
S:=S+Format('%5D',[I]);
If (Cnt mod 5)=0 then S:=S+CRLF;
end;
Memo.Lines.Add(S);
Memo.Lines.Add('Count = '+IntToStr(Cnt));
end;
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 Count = 50 Elapsed Time: 3.008 ms.
EasyLang
fastfunc isprim num .
i = 2
while i <= sqrt num
if num mod i = 0
return 0
.
i += 1
.
return 1
.
fastfunc nextprim prim .
repeat
prim += 1
until isprim prim = 1
.
return prim
.
func digok n .
d = 9
while n > 0
dp = d
d = n mod 10
if dp < d
return 0
.
n = n div 10
.
return 1
.
p = 2
repeat
if digok p = 1
write p & " "
.
p = nextprim p
until p >= 1000
.
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
F#
This task uses Extensible Prime Generator (F#)
// Primes with digits in nondecreasing order: Nigel Galloway. May 16th., 2021
let rec fN g=function n when n<10->(n<=g) |n when (n%10)<=g->fN(n%10)(n/10) |_->false
let fN=fN 9 in primes32()|>Seq.takeWhile((>)1000)|>Seq.filter fN|>Seq.iter(printf "%d "); printfn ""
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
Factor
USING: grouping lists lists.lazy math math.primes.lists
present prettyprint ;
lprimes [ present [ <= ] monotonic? ] lfilter
[ 1000 < ] lwhile [ . ] leach
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
J
echo (([:*./2<:/\10#.^:_1])"0#])@(i.&.(p:^:_1)) 1000
exit 0
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
FreeBASIC
#include "isprime.bas"
function is_ndp( byval n as integer ) as boolean
'reads from the least significant digit first
dim as integer d=10, ld
do
ld = d
d = n mod 10
if d > ld then return false
n = n\10
loop until n = 0
return true
end function
for i as uinteger = 2 to 999
if isprime(i) andalso is_ndp(i) then print i;" ";
next i : print
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
Frink
for n = primes[2,1000]
if sort[integerDigits[n]] == integerDigits[n]
print["$n "]
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
Go
package main
import (
"fmt"
"rcu"
)
func nonDescending(p int) bool {
var digits []int
for p > 0 {
digits = append(digits, p%10)
p = p / 10
}
for i := 0; i < len(digits)-1; i++ {
if digits[i+1] > digits[i] {
return false
}
}
return true
}
func main() {
primes := rcu.Primes(999)
var nonDesc []int
for _, p := range primes {
if nonDescending(p) {
nonDesc = append(nonDesc, p)
}
}
fmt.Println("Primes below 1,000 with digits in non-decreasing order:")
for i, n := range nonDesc {
fmt.Printf("%3d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n%d such primes found.\n", len(nonDesc))
}
- Output:
Primes below 1,000 with digits in non-decreasing order: 2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 50 such primes found.
jq
Works with gojq, the Go implementation of jq
See e.g. Erdős-primes#jq for a suitable implementation of `is_prime`.
def digits: tostring | explode;
# Input: an upper bound, or `infinite`
# Output: a stream
def primes_with_nondecreasing_digits:
(2, range(3; .; 2))
| select( (digits | (. == sort)) and is_prime);
1000 | primes_with_nondecreasing_digits
- Output:
(abbreviated)
2 3 5 7 11 ... 557 569 577 599 677
Julia
Note for the case-sensitive digits base 62 example: Julia defaults to 'A' < 'a' in sorting. So Aa is in order, but aA is not nondecreasing.
using Primes
const range = 2:999
for base in [2:10...;[16, 17, 27, 31, 62]]
primes = filter(n -> isprime(n) && issorted(digits(n, base=base), rev=true), range)
println("\nBase $base: ", length(primes), " non-descending primes between 1 and ",
string(last(primes), base=base), ":")
foreach(p -> print(lpad(string(p[2], base=base), 5), p[1] % 16 == 0 ? "\n" : ""), enumerate(primes))
end
- Output:
Base 2: 4 non-descending primes between 1 and 1111111: 11 111111111111111 Base 3: 6 non-descending primes between 1 and 1222: 2 12 111 122 1112 1222 Base 4: 17 non-descending primes between 1 and 22223: 2 3 11 13 23 113 133 223 233 1223 1333 233311123112331133312233 22223 Base 5: 17 non-descending primes between 1 and 12222: 2 3 12 23 34 111 122 133 1112 1123 1233 1244 2223 2344 344411122 12222 Base 6: 37 non-descending primes between 1 and 3555: 2 3 5 11 15 25 35 45 111 115 125 135 155 225 245 255 335 345 445 455 1115 1125 1145 1235 1245 1335 1345 1355 1445 1555 2225 2335 2345 2555 3445 3455 3555 Base 7: 38 non-descending primes between 1 and 2555: 2 3 5 14 16 23 25 56 113 115 124 133 146 155 166 245 256 335 344 346 445 566 1112 1123 1136 1156 1222 1226 1235 1345 1444 1466 2234 2236 2333 2335 2366 2555 Base 8: 47 non-descending primes between 1 and 1567: 2 3 5 7 13 15 23 27 35 37 45 57 111 117 123 145 147 155 177 225 227 235 247 255 277 337 345 357 445 467 557 577 667 1113 1127 1137 1145 1167 1223 1225 1245 1335 1347 1357 1467 1555 1567 Base 9: 45 non-descending primes between 1 and 1288: 2 3 5 7 12 14 18 25 34 45 47 58 67 78 117 122 124 128 135 155 177 234 238 267 278 337 344 355 377 447 557 568 667 678 788 1112 1114 1118 1147 1158 1178 1222 1255 1268 1288 Base 10: 50 non-descending primes between 1 and 677: 2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 Base 16: 88 non-descending primes between 1 and 3df: 2 3 5 7 b d 11 13 17 1d 1f 25 29 2b 2f 35 3b 3d 47 49 4f 59 67 6b 6d 7f 89 8b 9d ad bf df ef 115 119 11b 125 133 137 139 13d 14b 15b 15d 167 16f 17b 17f 18d 199 1af 1bb 1cd 1cf 1df 223 22d 233 239 23b 24b 257 259 25f 269 26b 277 28d 2ab 2bd 2cf 2dd 2ef 335 337 33b 33d 347 355 359 35b 35f 36d 377 38b 38f 3ad 3df Base 17: 82 non-descending primes between 1 and 37b: 2 3 5 7 b d 12 16 1c 1e 23 27 29 2d 38 3a 3g 45 4b 4f 5c 5g 67 6b 78 7c 8d 8f 9a 9e ab bc fg 111 115 117 11b 128 12e 137 139 13d 14a 14g 155 159 15f 166 16a 17b 17d 188 18e 19f 1bb 1bf 1cg 1dd 1ee 1gg 225 227 23c 23e 247 24d 24f 25a 25e 26b 27c 28d 29c 2ad 2cf 33b 346 34c 35f 368 36e 37b Base 27: 103 non-descending primes between 1 and 19p: 2 3 5 7 b d h j n 12 14 1a 1e 1g 1k 1q 25 27 2d 2h 2j 2p 38 3g 3k 3m 3q 45 4j 4n 5e 5g 5m 6b 6h 6j 78 7a 7m 8b 8d 8h 8n 8p 9e 9k 9q ab ad an be bg bk cd cn cp dg dm ej en fg fq gh gp hk in kn lq mn mp nq op pq 111 115 11d 11h 124 12e 12q 13b 13d 13h 13j 14g 14k 14m 14q 15d 15h 15j 15n 16g 16k 17b 17j 17n 188 18m 18q 19b 19j 19p Base 31: 94 non-descending primes between 1 and 115: 2 3 5 7 b d h j n t 16 1a 1c 1g 1m 1s 1u 25 29 2b 2h 2l 2r 34 38 3a 3e 3g 3k 47 4d 4f 4p 4r 58 5c 5i 5o 5q 67 6b 6d 6p 7a 7c 7g 7m 7o 89 8f 8l 8n 8t 9e 9s al ar bc bi bq ch cp ct dg di ds du ef en er et fm fq gp gr hk hu ij it jo js ju kl kn kr lm lq mr nq nu op ot tu 115 Base 62: 150 non-descending primes between 1 and Fz: 2 3 5 7 B D H J N T V b f h l r x z 15 19 1B 1H 1L 1R 1Z 1d 1f 1j 1l 1p 23 27 2D 2F 2P 2R 2X 2d 2h 2n 2t 2v 35 37 3B 3D 3P 3b 3f 3h 3l 3r 3t 49 4F 4L 4N 4T 4X 4Z 4j 4x 57 5L 5R 5b 5d 5h 5n 5v 67 6B 6H 6P 6T 6b 6l 6n 6x 6z 79 7F 7N 7R 7T 7X 7j 7r 7v 8D 8P 8R 8j 8p 8z 9B 9D 9J 9T 9Z 9f 9h 9n 9t 9x 9z AB AL AN AR AX Ad Af Ar Av BJ BR Bb Bj Bp Bv Bz CD CH CP CT Ch Cr DF DH DL DN DX Dl Dp Dr Dv EF EJ Ed Eh Ep Ez FH FN Fb Ff Fl Fr Fz
Ksh
#!/bin/ksh
# Primes with digits in nondecreasing order
# # Variables:
#
integer MAXPRIME=1000 MINPRIME=2
# # 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
}
# # Function _isnondecreasing(n) return 1 when digits nondecreasing
#
function _isnondecreasing {
typeset _n ; integer _n=$1
typeset _i ; integer _i
(( ${#_n} < 2 )) && return 1 # Always for single digit
for((_i=0; _i<${#_n}-1; _i++)); do
(( ${_n:${_i}:1} > ${_n:$((_i+1)):1} )) && return 0
done
return 1
}
######
# main #
######
integer i cnt=0
for ((i=MINPRIME; i<MAXPRIME; i++)); do
_isprime ${i} && (( ! $? )) && continue
_isnondecreasing ${i} && (( ! $? )) && continue
(( cnt++ )) && printf " %d" ${i}
done
printf "\n%d Primes with digits in nondecreasing order < %d\n" ${cnt} $MAXPRIME
- Output:
3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 67750 Primes with digits in nondecreasing order < 1000
MAD
NORMAL MODE IS INTEGER
BOOLEAN PRIME
DIMENSION PRIME(1000), COL(10)
PRIME(0) = 0B
PRIME(1) = 0B
SQMAX=SQRT.(1000)
THROUGH INIT, FOR I=2, 1, I.G.1000
INIT PRIME(I) = 1B
THROUGH SIEVE, FOR I=2, 1, I.G.SQMAX
WHENEVER PRIME(I)
THROUGH SIEVE2, FOR J=I+I, I, J.G.1000
SIEVE2 PRIME(J) = 0B
END OF CONDITIONAL
SIEVE CONTINUE
C = 1
THROUGH TEST, FOR D100=0, 1, D100.G.9
THROUGH TEST, FOR D10=D100, 1, D10.G.9
THROUGH TEST, FOR D1=D10, 1, D1.G.9
N = D100*100+D10*10+D1
WHENEVER PRIME(N)
COL(C) = N
C = C+1
WHENEVER C.G.10
PRINT FORMAT CFMT,COL(1),COL(2),COL(3),COL(4),
0 COL(5),COL(6),COL(7),COL(8),COL(9),COL(10)
C = 1
END OF CONDITIONAL
END OF CONDITIONAL
TEST CONTINUE
VECTOR VALUES CFMT = $10(I4)*$
END OF PROGRAM
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
Mathematica / Wolfram Language
Partition[
Cases[Most@
NestWhileList[NextPrime,
2, # < 1000 &], _?(OrderedQ[IntegerDigits@#] &)],
UpTo[10]] // TableForm
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
Nim
import strformat, sugar
func isPrime(n: Natural): bool =
if n < 2: return false
if n mod 2 == 0: return n == 2
if n mod 3 == 0: return n == 3
var d = 5
while d * d <= n:
if n mod d == 0: return false
inc d, 2
if n mod d == 0: return false
inc d, 4
result = true
func isNonDecreasing(n: int): bool =
var n = n
var prev = 10
while n != 0:
let d = n mod 10
if d > prev: return false
prev = d
n = n div 10
result = true
let result = collect(newSeq):
for n in 2..999:
if n.isPrime and n.isNonDecreasing: n
echo &"Found {result.len} primes:"
for i, n in result:
stdout.write &"{n:3}", if (i + 1) mod 10 == 0: '\n' else: ' '
- Output:
Found 50 primes: 2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
Phix
function nd(string s) return s=sort(s) end function sequence res = filter(apply(true,sprintf,{{"%d"},get_primes_le(1000)}),nd) printf(1,"%d non-decreasing primes < 1,000: %s\n",{length(res),join(shorten(res,"",5))})
- Output:
50 non-decreasing primes < 1,000: 2 3 5 7 11 ... 557 569 577 599 677
Perl
#!/usr/bin/perl
use strict;
use warnings;
use ntheory qw( primes );
my @want = grep ! /(.)(.)(??{$1 > $2 ? '' : '(*FAIL)'})/, @{ primes(1000) };
print "@want" =~ s/.{50}\K /\n/gr . "\n\ncount: " . @want . "\n";
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 count: 50
Plain English
To run:
Start up.
Loop.
If a counter is past 1000, break.
If the counter is prime and non-decreasing, write the counter then " " on the console without advancing.
Repeat.
Wait for the escape key.
Shut down.
To decide if a number is non-decreasing:
Privatize the number.
Put 10 into a previous digit number.
Loop.
Divide the number by 10 giving a quotient and a remainder.
If the remainder is greater than the previous digit, say no.
Put the remainder into the previous digit.
Put the quotient into the number.
If the number is 0, say yes.
Repeat.
To decide if a number is prime and non-decreasing:
If the number is not prime, say no.
If the number is not non-decreasing, say no.
Say yes.
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
PL/M
100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (6) BYTE INITIAL ('.....$');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
SIEVE: PROCEDURE (MAX, PBASE);
DECLARE (MAX, PBASE) ADDRESS, P BASED PBASE BYTE;
DECLARE (I, J) ADDRESS;
P(0)=0;
P(1)=0;
DO I=2 TO MAX; P(I)=1; END;
DO I=2 TO MAX/2;
IF P(I) THEN
DO J=I+I TO MAX BY I;
P(J)=0;
END;
END;
END SIEVE;
DECLARE (D$100, D$10, D$1, COL) BYTE;
DECLARE P (1000) BYTE;
DECLARE N ADDRESS;
CALL SIEVE(LAST(P), .P);
COL = 0;
DO D$100 = 0 TO 9;
DO D$10 = D$100 TO 9;
DO D$1 = D$10 TO 9;
N = D$100*100 + D$10*10 + D$1;
IF P(N) THEN DO;
CALL PRINT$NUMBER(N);
IF COL < 9 THEN DO;
COL = COL + 1;
CALL PRINT(.(9,36));
END;
ELSE DO;
COL = 0;
CALL PRINT(.(13,10,36));
END;
END;
END;
END;
END;
CALL EXIT;
EOF
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
Python
'''Primes with monotonic (rising or equal) digits'''
from operator import le
from itertools import takewhile
# monotonicDigits :: Int -> Int -> Bool
def monotonicDigits(base):
'''True if the decimal digits of n
are monotonic under (<=)
'''
def go(n):
return monotonic(le)(
showIntAtBase(base)(digitFromInt)(n)('')
)
return go
# monotonic :: (a -> a -> Bool) -> [a] -> Bool
def monotonic(op):
'''True if the op returns True for each
successive pair of values in xs.
'''
def go(xs):
return all(map(op, xs, xs[1:]))
return go
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Primes below 1000 in which any decimal digit is
lower than or equal to any digit to its right.
'''
xs = [
str(n) for n in takewhile(
lambda n: 1000 > n,
filter(monotonicDigits(10), primes())
)
]
w = len(xs[-1])
print(f'{len(xs)} matches for base 10:\n')
print('\n'.join(
' '.join(row) for row in chunksOf(10)([
x.rjust(w, ' ') for x in xs
])
))
# ----------------------- GENERIC ------------------------
# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
'''A series of lists of length n, subdividing the
contents of xs. Where the length of xs is not evenly
divible, the final list will be shorter than n.
'''
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
# digitFromInt :: Int -> Char
def digitFromInt(n):
'''A character representing a small
integer value.
'''
return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if (
0 <= n < 36
) else '?'
# 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
# showIntAtBase :: Int -> (Int -> Char) -> Int ->
# String -> String
def showIntAtBase(base):
'''String representation of an integer in a given base,
using a supplied function for the string
representation of digits.
'''
def wrap(toChr, n, rs):
def go(nd, r):
n, d = nd
r_ = toChr(d) + r
return go(divmod(n, base), r_) if 0 != n else r_
return 'unsupported base' if 1 >= base else (
'negative number' if 0 > n else (
go(divmod(n, base), rs))
)
return lambda toChr: lambda n: lambda rs: (
wrap(toChr, n, rs)
)
# MAIN ---
if __name__ == '__main__':
main()
- Output:
50 matches for base 10: 2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
Quackery
isprime
is defined at Primality by trial division#Quackery.
[ true 10 rot
[ 10 /mod rot
dip tuck > iff
[ rot not unrot ]
done
dup 0 = until ]
2drop ] is nondecreasing ( n --> b )
[] 1000 times
[ i^ nondecreasing while
i^ isprime while
i^ join ]
echo
- Output:
[ 2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 ]
Raku
my $range = ^1000;
for flat 2..10, 17, 27, 31 -> $base {
say "\nBase $base: {+$_} non-decending primes between $range.minmax.map( *.base: $base ).join(' and '):\n{
.batch(20)».fmt("%{.tail.chars}s").join: "\n" }"
given $range.grep( *.is-prime ).map( *.base: $base ).grep: { [le] .comb }
}
- Output:
Base 2: 4 non-decending primes between 0 and 1111100111: 11 111 11111 1111111 Base 3: 6 non-decending primes between 0 and 1101000: 2 12 111 122 1112 1222 Base 4: 17 non-decending primes between 0 and 33213: 2 3 11 13 23 113 133 223 233 1223 1333 2333 11123 11233 11333 12233 22223 Base 5: 17 non-decending primes between 0 and 12444: 2 3 12 23 34 111 122 133 1112 1123 1233 1244 2223 2344 3444 11122 12222 Base 6: 37 non-decending primes between 0 and 4343: 2 3 5 11 15 25 35 45 111 115 125 135 155 225 245 255 335 345 445 455 1115 1125 1145 1235 1245 1335 1345 1355 1445 1555 2225 2335 2345 2555 3445 3455 3555 Base 7: 38 non-decending primes between 0 and 2625: 2 3 5 14 16 23 25 56 113 115 124 133 146 155 166 245 256 335 344 346 445 566 1112 1123 1136 1156 1222 1226 1235 1345 1444 1466 2234 2236 2333 2335 2366 2555 Base 8: 47 non-decending primes between 0 and 1747: 2 3 5 7 13 15 23 27 35 37 45 57 111 117 123 145 147 155 177 225 227 235 247 255 277 337 345 357 445 467 557 577 667 1113 1127 1137 1145 1167 1223 1225 1245 1335 1347 1357 1467 1555 1567 Base 9: 45 non-decending primes between 0 and 1330: 2 3 5 7 12 14 18 25 34 45 47 58 67 78 117 122 124 128 135 155 177 234 238 267 278 337 344 355 377 447 557 568 667 678 788 1112 1114 1118 1147 1158 1178 1222 1255 1268 1288 Base 10: 50 non-decending primes between 0 and 999: 2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 Base 17: 82 non-decending primes between 0 and 37D: 2 3 5 7 B D 12 16 1C 1E 23 27 29 2D 38 3A 3G 45 4B 4F 5C 5G 67 6B 78 7C 8D 8F 9A 9E AB BC FG 111 115 117 11B 128 12E 137 139 13D 14A 14G 155 159 15F 166 16A 17B 17D 188 18E 19F 1BB 1BF 1CG 1DD 1EE 1GG 225 227 23C 23E 247 24D 24F 25A 25E 26B 27C 28D 29C 2AD 2CF 33B 346 34C 35F 368 36E 37B Base 27: 103 non-decending primes between 0 and 1A0: 2 3 5 7 B D H J N 12 14 1A 1E 1G 1K 1Q 25 27 2D 2H 2J 2P 38 3G 3K 3M 3Q 45 4J 4N 5E 5G 5M 6B 6H 6J 78 7A 7M 8B 8D 8H 8N 8P 9E 9K 9Q AB AD AN BE BG BK CD CN CP DG DM EJ EN FG FQ GH GP HK IN KN LQ MN MP NQ OP PQ 111 115 11D 11H 124 12E 12Q 13B 13D 13H 13J 14G 14K 14M 14Q 15D 15H 15J 15N 16G 16K 17B 17J 17N 188 18M 18Q 19B 19J 19P Base 31: 94 non-decending primes between 0 and 117: 2 3 5 7 B D H J N T 16 1A 1C 1G 1M 1S 1U 25 29 2B 2H 2L 2R 34 38 3A 3E 3G 3K 47 4D 4F 4P 4R 58 5C 5I 5O 5Q 67 6B 6D 6P 7A 7C 7G 7M 7O 89 8F 8L 8N 8T 9E 9S AL AR BC BI BQ CH CP CT DG DI DS DU EF EN ER ET FM FQ GP GR HK HU IJ IT JO JS JU KL KN KR LM LQ MR NQ NU OP OT TU 115
REXX
/*REXX program finds & displays primes whose decimal digits are in non─decreasing order.*/
parse arg n cols . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 1000 /*Not specified? Then use the default.*/
if cols=='' | cols=="," then cols= 10 /* " " " " " " */
call genP /*build array of semaphores for primes.*/
w= 10 /*width of a number in any column. */
title= ' primes whose decimal digits are in' ,
'non─decreasing order, N < ' commas(n)
if cols>0 then say ' index │'center(title, 1 + cols*(w+1) )
if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─')
found= 0; idx= 1 /*initialize # of non─decreasing primes*/
$= /*a list of non─decreasing digit primes*/
do j=1 while @.j<n; p= @.j /*examine the primes within the range. */
do k=1 for length(p)-1 /*validate that it meets specifications*/
if substr(p, k, 1) > substr(p, k+1, 1) then iterate j /*compare dig with next.*/
end /*k*/
found= found + 1 /*bump number of non─decreasing primes.*/
if cols<0 then iterate /*Just do the summary? Then skip grid.*/
$= $ right( commas(j), w) /*add a commatized prime──►list (grid).*/
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), '─') /*display foot sep. */
say
say 'Found ' commas(found) title /*display foot title*/
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 /*define some low primes. */
#= 3; s.#= @.# **2 /*number of primes so far; prime². */
/* [↓] generate more primes ≤ high.*/
do j=@.#+2 by 2 to n-1 /*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? */
/* [↑] the above five lines saves time*/
do k=4 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 /*bump # of Ps; assign next P; P²; P# */
end /*j*/; return
- output when using the default inputs:
index │ primes whose decimal digits are in non─decreasing order, N < 1,000 ───────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────── 1 │ 1 2 3 4 5 6 7 8 9 10 11 │ 12 15 17 19 22 24 30 31 33 34 21 │ 35 37 39 41 46 48 49 50 51 52 31 │ 55 57 59 68 69 70 72 73 75 77 41 │ 87 88 91 92 95 102 104 106 109 123 ───────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────── Found 50 primes whose decimal digits are in non─decreasing order, N < 1,000
Ring
load "stdlib.ring"
? "working..."
c = 0
limit = 1000
? "Primes under " + limit + " with digits in nondecreasing order:"
for n = 1 to limit
flag = 1
strn = string(n)
if isprime(n)
for m = 1 to len(strn) - 1
if strn[m] > strn[m + 1]
flag = 0
exit
ok
next
if flag = 1
see sf(n, 4) + " "
c++ if c % 10 = 0 see nl ok
ok
ok
next
? nl + "Found " + c + " base 10 primes with digits in nondecreasing order"
? "done..."
# a very plain string formatter, intended to even up columnar outputs
def sf x, y
s = string(x) l = len(s)
if l > y y = l ok
return substr(" ", 11 - y + l) + s
- Output:
working... Primes under 1000 with digits in nondecreasing order: 2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 Found 50 base 10 primes with digits in nondecreasing order done...
RPL
« →STR { 0 0 } 1 PICK3 SIZE FOR j OVER j DUP SUB STR→ + NEXT NIP ΔLIST « MIN » STREAM 0 ≥ » 'NONDEC?' STO « { } 2 WHILE DUP 1000 < REPEAT IF DUP NONDEC? THEN SWAP OVER + SWAP END NEXTPRIME END DROP DUP SIZE » 'TASK' STO
- Output:
2: {2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677} 1: 50.
Ruby
require 'prime'
base = 10
upto = 1000
res = Prime.each(upto).select do |pr|
pr.digits(base).each_cons(2).all?{|p1, p2| p1 >= p2}
end
puts "There are #{res.size} non-descending primes below #{upto}:"
puts res.join(", ")
- Output:
There are 50 non-descending primes below 1000: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 37, 47, 59, 67, 79, 89, 113, 127, 137, 139, 149, 157, 167, 179, 199, 223, 227, 229, 233, 239, 257, 269, 277, 337, 347, 349, 359, 367, 379, 389, 449, 457, 467, 479, 499, 557, 569, 577, 599, 677
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 func boolean: isNondecreasing (in var integer: number) is func
result
var boolean: nondecreasing is TRUE;
local
var integer: previousDigit is 10;
var integer: currentDigit is 0;
begin
while number <> 0 and nondecreasing do
currentDigit := number rem 10;
if currentDigit > previousDigit then
nondecreasing := FALSE;
end if;
number := number div 10;
previousDigit := currentDigit;
end while;
end func;
const proc: main is func
local
var integer: n is 0;
begin
write("2 ");
for n range 3 to 999 step 2 do
if isPrime(n) and isNondecreasing(n) then
write(n <& " ");
end if;
end for;
end func;
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677
Sidef
Simple solution:
say 1000.primes.grep { .digits.cons(2).all { .head >= .tail } }
Generate such primes from digits (asymptotically faster):
func primes_with_nondecreasing_digits(upto, base = 10) {
upto = prev_prime(upto+1)
var list = []
var digits = @(1..^base -> flip)
var end_digits = digits.grep { .is_coprime(base) }
list << digits.grep { .is_prime && !.is_coprime(base) }...
for k in (0 .. upto.ilog(base)) {
digits.combinations_with_repetition(k, {|*a|
var v = a.digits2num(base)
next if (v*base + end_digits.tail > upto)
end_digits.each {|d|
var n = (v*base + d)
next if ((n >= base) && (a[0] > d))
list << n if n.is_prime
}
})
}
list.sort
}
say primes_with_nondecreasing_digits(1000)
- Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 37, 47, 59, 67, 79, 89, 113, 127, 137, 139, 149, 157, 167, 179, 199, 223, 227, 229, 233, 239, 257, 269, 277, 337, 347, 349, 359, 367, 379, 389, 449, 457, 467, 479, 499, 557, 569, 577, 599, 677]
Visual Basic .NET
Imports System.Linq
Imports System.Collections.Generic
Imports System.Console
Imports System.Math
Module Module1
Dim ba As Integer
Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)
Dim flags(lim) As Boolean, j As Integer : Yield 2
For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3
Dim d As Integer = 8, sq As Integer = 9
While sq <= lim
If Not flags(j) Then
Yield j : Dim i As Integer = j << 1
For k As Integer = sq To lim step i : flags(k) = True : Next
End If
j += 2 : d += 8 : sq += d : End While
While j <= lim
If Not flags(j) Then Yield j
j += 2 : End While
End Function
' convert an int into a string using the current ba
Function from10(ByVal b As Integer) As String
Dim res As String = "", re As Integer
While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res
End Function
' parse a string into an int, using current ba (not used here)
Function to10(ByVal s As String) As Integer
Dim res As Integer = 0
For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res
End Function
' note: comparing the index of the chars instead of the chars themsleves, which avoids case issues
Function nd(ByVal s As String) As Boolean
If s.Length < 2 Then Return True
Dim l As Char = s(0)
For i As Integer = 1 To s.Length - 1
If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)
Next : Return True
End Function
Sub Main(ByVal args As String())
Dim c As Integer, lim As Integer = 1000, s As String
For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }
ba = b : c = 0 : For Each a As Integer In Primes(lim)
s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, ""))
Next
WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim))
Next
End Sub
End Module
- Output:
Same as C#.
Wren
import "./math" for Int
import "./fmt" for Fmt
var nonDescending = Fn.new { |p|
var digits = []
while (p > 0) {
digits.add(p % 10)
p = (p/10).floor
}
for (i in 0...digits.count-1) {
if (digits[i+1] > digits[i]) return false
}
return true
}
var primes = Int.primeSieve(999)
var nonDesc = []
for (p in primes) if (nonDescending.call(p)) nonDesc.add(p)
System.print("Primes below 1,000 with digits in non-decreasing order:")
Fmt.tprint("$3d", nonDesc, 10)
System.print("\n%(nonDesc.count) such primes found.")
- Output:
Primes below 1,000 with digits in non-decreasing order: 2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 50 such primes found.
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 Nondecreasing(N);
\Return 'true' if N has left-to-right nondecreasing digits
\Or return 'true' if N has right-to-left nonincreasing digits
int N, D, D0;
[N:= N/10;
D0:= rem(0);
while N do
[N:= N/10;
D:= rem(0);
if D > D0 then return false;
D0:= D;
];
return true;
];
int Count, N;
[Count:= 0;
for N:= 0 to 1000-1 do
if IsPrime(N) and Nondecreasing(N) then
[IntOut(0, N);
Count:= Count+1;
if rem(Count/10) = 0 then CrLf(0) else ChOut(0, 9\tab\);
];
CrLf(0);
IntOut(0, Count);
Text(0, " primes found with nondecreasing digits below 1000.
");
]
- Output:
2 3 5 7 11 13 17 19 23 29 37 47 59 67 79 89 113 127 137 139 149 157 167 179 199 223 227 229 233 239 257 269 277 337 347 349 359 367 379 389 449 457 467 479 499 557 569 577 599 677 50 primes found with nondecreasing digits below 1000.
- Draft Programming Tasks
- Prime Numbers
- 11l
- Action!
- Action! Sieve of Eratosthenes
- ALGOL 68
- ALGOL 68-primes
- APL
- Arturo
- AWK
- BASIC
- BASIC256
- PureBasic
- Yabasic
- BCPL
- C sharp
- Delphi
- SysUtils,StdCtrls
- EasyLang
- F Sharp
- Factor
- J
- FreeBASIC
- Frink
- Go
- Go-rcu
- Jq
- Julia
- Ksh
- MAD
- Mathematica
- Wolfram Language
- Nim
- Phix
- Perl
- Ntheory
- Plain English
- PL/M
- Python
- Quackery
- Raku
- REXX
- Ring
- RPL
- Ruby
- Seed7
- Sidef
- Visual Basic .NET
- Wren
- Wren-math
- Wren-fmt
- XPL0