Unprimeable numbers: Difference between revisions
m
→{{header|Wren}}: Minor tidy
mNo edit summary |
m (→{{header|Wren}}: Minor tidy) |
||
(17 intermediate revisions by 13 users not shown) | |||
Line 51:
:* from the Adam Spencer book (page 200): ''Adam Spencer's World of Numbers'' (Xoum Publishing)
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V limit = 10'000'000
V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
I is_prime[n]
L(i) (n * n .< limit + 1).step(n)
is_prime[i] = 0B
F unprimeable(a)
I :is_prime[a]
R 0B
V d = 1
L d <= a
V base = (a I/ (d * 10)) * (d * 10) + (a % d)
I any((base .< base + d * 10).step(d).map(y -> :is_prime[y]))
R 0B
d *= 10
R 1B
F unprime(n)
[Int] r
L(a) 1..
I unprimeable(a)
r [+]= a
I r.len == n
L.break
R r
print(‘First 35:’)
print(unprime(35).map(i -> String(i)).join(‘ ’))
print("\nThe 600-th:")
print(unprime(600).last)
print()
V first = [0] * 10
V need = 10
L(p) 1..
I unprimeable(p)
V i = p % 10
I first[i] != 0
L.continue
first[i] = p
I --need == 0
L.break
L(v) first
print(L.index‘ ending: ’v)</syntaxhighlight>
{{out}}
<pre>
First 35:
200 204 206 208 320 322 324 325 326 328 510 512 514 515 516 518 530 532 534 535 536 538 620 622 624 625 626 628 840 842 844 845 846 848 890
The 600-th:
5242
0 ending: 200
1 ending: 595631
2 ending: 322
3 ending: 1203623
4 ending: 204
5 ending: 325
6 ending: 206
7 ending: 872897
8 ending: 208
9 ending: 212159
</pre>
=={{header|ALGOL 68}}==
If running this with Algol 68G under Windows (and possibly other platforms) you will need to increase the heap size by specifying e.g. <code>-heap 256M</code> on the command line.
{{libheader|ALGOL 68-primes}}
<syntaxhighlight lang="algol68">BEGIN # find unprimable numbers - numbers which can't be made into a prime by changing one digit #
# construct a sieve of primes up to max prime #
PR read "primes.incl.a68" PR
INT max prime = 9 999 999;
[]BOOL prime = PRIMESIEVE max prime;
# returns TRUE if n is unprimeable, FALSE otherwise #
PROC is unprimeable = ( INT n )BOOL:
IF n < 100
THEN FALSE
ELIF prime[ n ]
THEN FALSE
ELIF
# need to try changing a digit #
INT last digit = n MOD 10;
INT leading digits = n - last digit;
prime[ leading digits + 1 ]
THEN FALSE
ELIF prime[ leading digits + 3 ] THEN FALSE
ELIF prime[ leading digits + 7 ] THEN FALSE
ELIF prime[ leading digits + 9 ] THEN FALSE
ELIF last digit = 2 OR last digit = 5
THEN
# the final digit is 2 or 5, changing the other digits can't make a prime #
# unless there is only one other digit which we change to 0 #
INT v := leading digits;
INT dc := 1;
WHILE ( v OVERAB 10 ) > 0 DO IF v MOD 10 /= 0 THEN dc +:= 1 FI OD;
dc /= 2
ELIF NOT ODD last digit
THEN TRUE # last digit is even - can't make a prime #
ELSE
# last digit is 1, 3, 7, 9: must try changing the other digoits #
INT m10 := 10;
INT r10 := 100;
BOOL result := TRUE;
WHILE result AND n > r10 DO
INT base = ( ( n OVER r10 ) * r10 ) + ( n MOD m10 );
FOR i FROM 0 BY m10 WHILE result AND i < r10 DO
result := NOT prime[ base + i ]
OD;
m10 *:= 10;
r10 *:= 10
OD;
IF result THEN
# still not unprimeable, try changing the first digit #
INT base = n MOD m10;
FOR i FROM 0 BY m10 WHILE result AND i < r10 DO
result := NOT prime[ base + i ]
OD
FI;
result
FI # is unprimeable # ;
# returns a string representation of n with commas #
PROC commatise = ( LONG LONG INT n )STRING:
BEGIN
STRING result := "";
STRING unformatted = whole( n, 0 );
INT ch count := 0;
FOR c FROM UPB unformatted BY -1 TO LWB unformatted DO
IF ch count <= 2 THEN ch count +:= 1
ELSE ch count := 1; "," +=: result
FI;
unformatted[ c ] +=: result
OD;
result
END; # commatise #
# find unprimeable numbers #
INT u count := 0;
INT d count := 0;
[ 0 : 9 ]INT first unprimeable := []INT( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 )[ AT 0 ];
FOR i FROM 100 WHILE i < UPB prime AND d count < 10 DO
IF is unprimeable( i ) THEN
u count +:= 1;
IF u count = 1 THEN
print( ( "First 35 unprimeable numbers: ", whole( i, 0 ) ) )
ELIF u count <= 35 THEN
print( ( " ", whole( i, 0 ) ) )
ELIF u count = 600 THEN
print( ( newline, "600th unprimeable number: ", commatise( i ) ) )
FI;
INT final digit = i MOD 10;
IF first unprimeable[ final digit ] = 0 THEN
# first unprimeable number with this final digit #
d count +:= 1;
first unprimeable[ final digit ] := i
FI
FI
OD;
# show the first unprimeable number that ends with each digit #
print( ( newline ) );
FOR i FROM 0 TO 9 DO
print( ( "First unprimeable number ending in "
, whole( i, 0 )
, ": "
, commatise( first unprimeable[ i ] )
, newline
)
)
OD
END</syntaxhighlight>
{{out}}
<pre>
First 35 unprimeable numbers: 200 204 206 208 320 322 324 325 326 328 510 512 514 515 516 518 530 532 534 535 536 538 620 622 624 625 626 628 840 842 844 845 846 848 890
600th unprimeable number: 5,242
First unprimeable number ending in 0: 200
First unprimeable number ending in 1: 595,631
First unprimeable number ending in 2: 322
First unprimeable number ending in 3: 1,203,623
First unprimeable number ending in 4: 204
First unprimeable number ending in 5: 325
First unprimeable number ending in 6: 206
First unprimeable number ending in 7: 872,897
First unprimeable number ending in 8: 208
First unprimeable number ending in 9: 212,159
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">unprimeable?: function [n][
if prime? n -> return false
nd: to :string n
loop.with:'i nd 'prevDigit [
loop `0`..`9` 'newDigit [
if newDigit <> prevDigit [
nd\[i]: newDigit
if prime? to :integer nd -> return false
]
]
nd\[i]: prevDigit
]
return true
]
cnt: 0
x: 1
unprimeables: []
while [cnt < 600][
if unprimeable? x [
unprimeables: unprimeables ++ x
cnt: cnt + 1
]
x: x + 1
]
print "First 35 unprimeable numbers:"
print first.n: 35 unprimeables
print ""
print ["600th unprimeable number:" last unprimeables]</syntaxhighlight>
{{out}}
<pre>First 35 unprimeable numbers:
200 204 206 208 320 322 324 325 326 328 510 512 514 515 516 518 530 532 534 535 536 538 620 622 624 625 626 628 840 842 844 845 846 848 890
600th unprimeable number: 5242</pre>
=={{header|C}}==
{{trans|C++}}
<
#include <locale.h>
#include <stdbool.h>
Line 184 ⟶ 415:
printf("\n600th unprimeable number: %'u\n", n);
uint32_t last_digit = n % 10;
if (lowest[last_digit] == 0) {
lowest[last_digit] = n;
++found;
Line 195 ⟶ 425:
printf("Least unprimeable number ending in %u: %'u\n" , i, lowest[i]);
return 0;
}</
{{out}}
Line 215 ⟶ 445:
=={{header|C++}}==
<
#include <cstdint>
#include "prime_sieve.hpp"
Line 284 ⟶ 514:
std::cout << "Least unprimeable number ending in " << i << ": " << lowest[i] << '\n';
return 0;
}</
Contents of prime_sieve.hpp:
<
#define PRIME_SIEVE_HPP
Line 338 ⟶ 568:
}
#endif</
{{out}}
Line 359 ⟶ 589:
=={{header|D}}==
{{trans|Java}}
<
import std.array;
import std.conv;
Line 458 ⟶ 688:
writefln(" %d is %,d", i, v);
}
}</
{{out}}
<pre>First 35 unprimeable numbers:
Line 483 ⟶ 713:
===The function===
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)]
<
// Unprimeable numbers. Nigel Galloway: May 4th., 2021
let rec fN i g e l=seq{yield! [0..9]|>Seq.map(fun n->n*g+e+l); if g>1 then let g=g/10 in yield! fN(i+g*(e/g)) g (e%g) i}
let fG(n,g)=fN(n*(g/n)) n (g%n) 0|>Seq.exists(isPrime)
let uP()=let rec fN n g=seq{yield! {n..g-1}|>Seq.map(fun g->(n,g)); yield! fN(g)(g*10)} in fN 1 10|>Seq.filter(fG>>not)|>Seq.map snd
</syntaxhighlight>
===The Task===
<
uP()|>Seq.take 35|>Seq.iter(printf "%d "); printfn ""
</syntaxhighlight>
{{out}}
<pre>
200 204 206 208 320 322 324 325 326 328 510 512 514 515 516 518 530 532 534 535 536 538 620 622 624 625 626 628 840 842 844 845 846 848 890
</pre>
<
printfn "600th unprimable number is %d" (uP()|>Seq.item 599)
</syntaxhighlight>
{{out}}
<pre>
600th unprimable number is 5242
</pre>
<
[0..9]|>Seq.iter(fun n->printfn "first umprimable number ending in %d is %d" n (uP()|>Seq.find(fun g->n=g%10)))
</syntaxhighlight>
{{out}}
<pre>
Line 523 ⟶ 753:
===Optimized for optional part of task===
The above general implementation can complete all of the task but takes over 1min for the optional part. The following completes the optional part in 3secs.
<
let uPx x=let rec fN n g=seq{yield! {n+x..10..g-1}|>Seq.map(fun g->(max 1 n,g)); yield! fN(g)(g*10)} in fN 0 10|>Seq.filter(fG>>not)|>Seq.map snd
[0..9]|>Seq.iter(fun n->printfn "first umprimable number ending in %d is %d" n (uPx n|>Seq.head))
</syntaxhighlight>
{{out}}
<pre>
Line 543 ⟶ 773:
=={{header|Factor}}==
{{works with|Factor|0.99 2019-10-06}}
<
lists.lazy.examples math math.functions math.primes math.ranges
math.text.utils prettyprint sequences tools.memory.private ;
Line 575 ⟶ 805:
"The first unprimeable number ending with" print
first-digits [ commas " %d: %9s\n" printf ] assoc-each</
{{out}}
<pre>
Line 597 ⟶ 827:
</pre>
=={{header|FreeBASIC}}==
<
Function isprime(n As Ulongint) As boolean
If (n=2) Or (n=3) Then Return 1
Line 649 ⟶ 879:
Next z
sleep
</syntaxhighlight>
<pre>
First 35
Line 668 ⟶ 898:
=={{header|Go}}==
Simple brute force (no sieves, memoization or bigint.ProbablyPrime) as there is not much need for speed here.
<
import (
Line 754 ⟶ 984:
fmt.Printf(" %d is: %9s\n", i, commatize(firstNum[i]))
}
}</
{{out}}
Line 775 ⟶ 1,005:
</pre>
=={{header|Haskell}}==
<
import Data.Numbers.Primes (isPrime)
import Data.List (find, intercalate)
Line 805 ⟶ 1,035:
lowest n = do
x <- find (\x -> x `mod` 10 == n) unPrimeable
pure (n, thousands $ show x)</
{{out}}
<pre>
Line 827 ⟶ 1,057:
=={{header|J}}==
Reshaping data is a strength of j.
<syntaxhighlight lang="j">
NB. replace concatenates at various ranks and in boxes to avoid fill
NB. the curtailed prefixes (}:\) with all of 0..9 (i.10) with the beheaded suffixes (}.\.)
Line 839 ⟶ 1,069:
assert 0 1 -: unprimable 193 200
</syntaxhighlight>
<pre>
NB. test 2e6 integers for unprimability
Line 859 ⟶ 1,089:
=={{header|Java}}==
<
public class UnprimeableNumbers {
Line 955 ⟶ 1,185:
}
</syntaxhighlight>
{{out}}
Line 976 ⟶ 1,206:
9 is 212,159
</pre>
=={{header|JavaScript}}==
Auxiliary function:
<syntaxhighlight lang="javascript">
Number.prototype.isPrime = function() {
let i = 2, num = this;
if (num == 0 || num == 1) return false;
if (num == 2) return true;
while (i <= Math.ceil(Math.sqrt(num))) {
if (num % i == 0) return false;
i++;
}
return true;
}
</syntaxhighlight>
Core function:
<syntaxhighlight lang="javascript">
function isUnprimable(num) {
if (num < 100 || num.isPrime()) return false;
let arr = num.toString().split('');
for (let x = 0; x < arr.length; x++) {
let lft = arr.slice(0, x),
rgt = arr.slice(x + 1);
for (let y = 0; y < 10; y++) {
let test = lft.join('') + y.toString() + rgt.join('');
if (parseInt(test).isPrime()) return false;
}
}
return true;
}
</syntaxhighlight>
Main function for output:
<syntaxhighlight lang="javascript">
let unprimeables = [],
endings = new Array(10).fill('-'),
c = 1;
function chkEnds(n) {
let e = n % 10;
if (endings[e] == '-') endings[e] = n;
}
console.time('I');
while (unprimeables.length < 1000) {
if (isUnprimable(c)) {
unprimeables.push(c);
chkEnds(c)
}
c++;
}
console.log('The first 35 unprimeables:');
console.log(unprimeables.slice(0,35).join(', '));
console.log(`The 600th unprimeable: ${unprimeables[599].toLocaleString('en')}`);
console.log(`The 1000th unprimable: ${unprimeables[999].toLocaleString('en')}`);
console.timeEnd('I');
console.time('II');
while (endings.includes('-')) {
c++;
if (isUnprimable(c)) chkEnds(c);
}
for (c = 0; c < endings.length; c++) {
console.log(`First unprimeable ending with ${c}: ${endings[c].toLocaleString('en')}`);
}
console.timeEnd('II');
</syntaxhighlight>
{{out}}
<pre>
The first 35 unprimeables:
200, 204, 206, 208, 320, 322, 324, 325, 326, 328, 510, 512, 514, 515, 516, 518, 530, 532, 534, 535, 536, 538, 620, 622, 624, 625, 626, 628, 840, 842, 844, 845, 846, 848, 890
The 600th unprimeable: 5,242
The 1000th unprimable: 8,158
I: 240ms - timer ended
First unprimeable ending with 0: 200
First unprimeable ending with 1: 595,631
First unprimeable ending with 2: 322
First unprimeable ending with 3: 1,203,623
First unprimeable ending with 4: 204
First unprimeable ending with 5: 325
First unprimeable ending with 6: 206
First unprimeable ending with 7: 872,897
First unprimeable ending with 8: 208
First unprimeable ending with 9: 212,159
II: 186884ms - timer ended
</pre>
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
See e.g. [[Erd%C5%91s-primes#jq]] for a suitable definition of `is_prime` as used here.
'''Preliminaries'''
<syntaxhighlight lang="jq">def digits: tostring | explode | map([.] | implode | tonumber);
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
</syntaxhighlight>
'''Unprimeables'''
<syntaxhighlight lang="jq">
def variants:
digits
| range(0; length) as $pos
| range(0;10) as $newdigit
| if .[$pos] == $newdigit then empty
else .[$pos] = $newdigit
| join("")|tonumber
end;
def is_unprimeable:
if is_prime or any(variants; is_prime) then false
else true
end;
def unprimeables:
range(4; infinite) | select(is_unprimeable);</syntaxhighlight>
'''The Tasks'''
<syntaxhighlight lang="jq">def task:
"First 35 unprimeables: ",
[limit(35; range(0;infinite) | select(is_unprimeable))],
"\nThe 600th unprimeable is \( nth(600 - 1; unprimeables) ).",
"\nDigit First unprimeable ending with that digit",
"-----------------------------------------------",
(range(0;10) as $dig
| first( range(0;infinite) | select((. % 10 == $dig) and is_unprimeable))
| " \($dig) \(lpad(9))" )
;
task</syntaxhighlight>
{{out}}
<pre>
First 35 unprimeables:
[200,204,206,208,320,322,324,325,326,328,510,512,514,515,516,518,530,532,534,535,536,538,620,622,624,625,626,628,840,842,844,845,846,848,890]
The 600th unprimeable is 5242.
Digit First unprimeable ending with that digit
-----------------------------------------------
0 200
1 595631
2 322
3 1203623
4 204
5 325
6 206
7 872897
8 208
9 212159
</pre>
=={{header|Julia}}==
<
function isunprimeable(n)
Line 1,002 ⟶ 1,386:
println(" $dig ", lpad(format(n, commas=true), 9))
end
</
<pre>
First 35 unprimeables: (200 204 206 208 320 322 324 325 326 328 510 512 514 515 516 518 530 532 534 535 536 538 620 622 624 625 626 628 840 842 844 845 846 848 890)
Line 1,024 ⟶ 1,408:
=={{header|Kotlin}}==
{{trans|Java}}
<
private val primes = BooleanArray(MAX)
Line 1,118 ⟶ 1,502:
}
}
}</
{{out}}
<pre>First 35 unprimeable numbers:
Line 1,138 ⟶ 1,522:
=={{header|Lua}}==
<
local function T(t) return setmetatable(t, {__index=table}) end
table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end
Line 1,187 ⟶ 1,571:
for i = 0, 9 do
print(" " .. i .. " is: " .. commafy(lowests[i]))
end</
{{out}}
<pre>The first 35 unprimable numbers are:
Line 1,205 ⟶ 1,589:
8 is: 208
9 is: 212,159</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[Unprimeable]
Unprimeable[in_Integer] := Module[{id, new, pos},
id = IntegerDigits[in];
pos = Catenate@Table[
Table[
new = id;
new[[d]] = n;
new
,
{n, 0, 9}
]
,
{d, Length[id]}
];
pos //= Map[FromDigits];
NoneTrue[pos, PrimeQ]
]
res = {};
PrintTemporary[Dynamic[{Length[res], i}]];
i = 0;
While[Length[res] < 600,
If[Unprimeable[i],
AppendTo[res, i]
];
i++
];
PrintTemporary[Dynamic[{lastdig, i}]];
out = Table[
i = lastdig;
While[! Unprimeable[i],
i += 10
];
i
,
{lastdig, 0, 9}
];
res[[;; 35]]
res[[600]]
lastdigit = IntegerDigits /* Last;
Print["Least unprimeable number ending in ", lastdigit[#], ": ", #] & /@ SortBy[out, lastdigit];</syntaxhighlight>
{{out}}
<pre>{200,204,206,208,320,322,324,325,326,328,510,512,514,515,516,518,530,532,534,535,536,538,620,622,624,625,626,628,840,842,844,845,846,848,890}
5242
Least unprimeable number ending in 0: 200
Least unprimeable number ending in 1: 595631
Least unprimeable number ending in 2: 322
Least unprimeable number ending in 3: 1203623
Least unprimeable number ending in 4: 204
Least unprimeable number ending in 5: 325
Least unprimeable number ending in 6: 206
Least unprimeable number ending in 7: 872897
Least unprimeable number ending in 8: 208
Least unprimeable number ending in 9: 212159</pre>
=={{header|Nim}}==
<
const N = 10_000_000
Line 1,255 ⟶ 1,697:
while not n.isUmprimeable:
inc n, 10
echo "Lowest unprimeable number ending in ", d, " is ", ($n).insertSep(',')</
{{out}}
Line 1,277 ⟶ 1,719:
{{trans|Go}} {{works with|Free Pascal}}{{works with|Delphi}}
Small improvement.When the check of value ending in "0" is not unprimable than I can jump over by 10, since the check already has checked those numbers ending in "1".."9".But in case of unprimable I am using a reduced version of the check<BR>Results in runtime reduced from 1.8 secs downto 0.667 now to 0.46
<
{$IFDEF FPC}{$Mode Delphi}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
Line 1,488 ⟶ 1,930:
writeln('There are ',TotalCnt,' unprimable numbers upto ',n);
{$IFNDEF UNIX}readln;{$ENDIF}
end.</
{{out}}
<pre style="font-size:84%">
Line 1,511 ⟶ 1,953:
Base 18= 2*3*3 :lowest digit 7 found first 10,921,015,789<BR>
bases that are prime find their different digits quite early.
<
{$IFDEF FPC}
{$Mode Delphi}
Line 1,927 ⟶ 2,369:
writeln('There are ',TotalCnt,' unprimable numbers upto ',n);
setlength(Primes,0);
end.</
{{out}}
<pre style="height:35ex">
Line 1,999 ⟶ 2,441:
{{trans|Raku}}
{{libheader|ntheory}}
<
use warnings;
use feature 'say';
Line 2,028 ⟶ 2,470:
while ($x += 10) { last if is_unprimeable($x) }
say "First unprimeable that ends with $_: " . sprintf "%9s", comma $x;
} 0..9;</
{{out}}
<pre>First 35 unprimeables:
Line 2,048 ⟶ 2,490:
=={{header|Phix}}==
{{trans|Go}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</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;">"The first 35 unprimeable numbers are:\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">:=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- counts all unprimeable numbers</span>
<span style="color: #000000;">countFirst</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">100</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">firstNum</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- stores the first unprimeable number ending with each digit</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">(),</span> <span style="color: #000000;">t1</span><span style="color: #0000FF;">=</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">countFirst</span><span style="color: #0000FF;"><</span><span style="color: #000000;">10</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- unprimeable number must be composite</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">le</span> <span style="color: #0000FF;">:=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">bool</span> <span style="color: #000000;">primeable</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">le</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'0'</span> <span style="color: #008080;">to</span> <span style="color: #008000;">'9'</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">k</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">b</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">k</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">to_integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">primeable</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">primeable</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">b</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- restore j'th digit to what it was originally</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">primeable</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">lastDigit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">le</span><span style="color: #0000FF;">]-</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">firstNum</span><span style="color: #0000FF;">[</span><span style="color: #000000;">lastDigit</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">==</span> <span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">firstNum</span><span style="color: #0000FF;">[</span><span style="color: #000000;">lastDigit</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span>
<span style="color: #000000;">countFirst</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;"><=</span> <span style="color: #000000;">35</span> <span style="color: #008080;">then</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;">"%d "</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">==</span> <span style="color: #000000;">600</span> <span style="color: #008080;">then</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;">"\n\nThe 600th unprimeable number is: %,d\n\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()></span><span style="color: #000000;">t1</span> <span style="color: #008080;">then</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;">"checking %d, %d `endswiths` found\r"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">countFirst</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</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;">"The first unprimeable number that ends in:\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</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;">" %d is: %,9d\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">firstNum</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,120 ⟶ 2,566:
=={{header|Pike}}==
Not the fastest way of doing this, but using string manipulation seemed like the obvious Pike way to do it.
<syntaxhighlight lang="pike">
bool is_unprimeable(int i)
{
Line 2,159 ⟶ 2,605:
write(" %s is: %9d\n", e, first_enders[e]);
}
}</
Output:
<pre>
Line 2,180 ⟶ 2,626:
=={{header|Python}}==
<
def primes(_cache=[2, 3]):
Line 2,231 ⟶ 2,677:
for i,v in enumerate(first):
print(f'{i} ending: {v}')</
{{out}}
<pre>First 35:
Line 2,253 ⟶ 2,699:
=={{header|Racket}}==
<
(require math/number-theory)
Line 2,299 ⟶ 2,745:
(check-equal? (primeable? 10) 11)
(check-true (unprimeable? 200))
(check-false (unprimeable? 201)))</
{{out}}
Line 2,318 ⟶ 2,764:
=={{header|Raku}}==
(formerly Perl 6)
{{libheader|ntheory}}
<syntaxhighlight lang="raku" line>use ntheory:from<Perl5> <is_prime>;
use Lingua::EN::Numbers;
Line 2,328 ⟶ 2,773:
for ^chrs -> \place {
my \pow = 10**(chrs - place - 1);
my \this = n.substr(place, 1)
^10 .map: -> \dgt {
next if this == dgt;
return False if is_prime(n - this + dgt
}
}
Line 2,346 ⟶ 2,791:
print "First unprimeable that ends with {n}: " ~
sprintf "%9s\n", comma (n, *+10 … *).race.first: { .&is-unprimeable }
}</
{{out}}
<pre>First 35 unprimeables:
Line 2,366 ⟶ 2,811:
=={{header|REXX}}==
Some effort was put into the optimization of the generation of primes (the '''genP''' subroutine).
With the addition of the computation of squared primes, the program now is about '''4''' times faster.
<syntaxhighlight lang="rexx">/*REXX program finds and displays unprimeable numbers (non─negative integers). */
parse arg n x hp . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 35 /*Not specified? Then use the default.*/
if x=='' | x=="," then x= 600 /* " " " " " " */
if hp=='' | hp=="," then hp= 10000000 /* " " " " " " */
eds=4; ed.1= 1; ed.2= 3; ed.3= 7; ed.4= 9 /*"end" digits which are prime; prime>9*/
call genP hp /*generate primes up to & including HP.*/
$$=; $.=. /*a list " " " " " */
do j=100; if !.j then iterate /*Prime? Unprimeable must be composite*/
Lm= length(j) /*obtain the length-1 of the number J. */
Line 2,398 ⟶ 2,844:
end /*n_*/
end /*a_*/
if
if
parse var j '' -1 _ /*obtain the right─most dec digit of J.*/
if $._==. then $._= j /*the 1st unprimeable # that ends in _.*/
Line 2,421 ⟶ 2,867:
th:procedure;parse arg x;return x||word('th st nd rd',1+(x//10)*(x//100%10\==1)*(x//10<4))
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=
!.=0;
#= 11; sq.#= @.# **2
do lim=100 until lim*lim>=hp /*only keep primes up to the sqrt(hp). */
end /*lim*/ /* [↑] find limit for storing primes. */
do j=@.#
if j//
if j//
if j//
end /*k*/ /* [↓] a prime (J) has been found. */
#
{{out|output|text= when using the default inputs:}}
Line 2,462 ⟶ 2,903:
</pre>
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">require 'prime'
def unprimable?(n)
digits = %w(0 1 2 3 4 5 6 7 8 9)
s = n.to_s
size = s.size
(size-1).downto(0) do |i|
digits.each do |d|
cand = s.dup
cand[i]=d
return false if cand.to_i.prime?
end
end
true
end
ups = Enumerator.new {|y| (1..).each{|n| y << n if unprimable?(n)} }
ar = ups.first(600)
puts "First 35 unprimables:", ar[0,35].join(" ")
puts "\n600th unprimable:", ar.last, ""
(0..9).each do |d|
print "First unprimeable with last digit #{d}: "
puts (1..).detect{|k| unprimable?(k*10+d)}*10 + d
end
</syntaxhighlight>
{{out}}
<pre>First 35 unprimables:
200 204 206 208 320 322 324 325 326 328 510 512 514 515 516 518 530 532 534 535 536 538 620 622 624 625 626 628 840 842 844 845 846 848 890
600th unprimable:
5242
First unprimeable with last digit 0: 200
First unprimeable with last digit 1: 595631
First unprimeable with last digit 2: 322
First unprimeable with last digit 3: 1203623
First unprimeable with last digit 4: 204
First unprimeable with last digit 5: 325
First unprimeable with last digit 6: 206
First unprimeable with last digit 7: 872897
First unprimeable with last digit 8: 208
First unprimeable with last digit 9: 212159
</pre>
=={{header|Rust}}==
{{trans|C++}}
<
mod bit_array;
mod prime_sieve;
Line 2,540 ⟶ 3,025:
println!("Least unprimeable number ending in {}: {}", i, lowest[i]);
}
}</
<
use crate::bit_array;
Line 2,577 ⟶ 3,062:
!self.composite.get(n / 2 - 1)
}
}</
<
pub struct BitArray {
array: Vec<u32>,
Line 2,602 ⟶ 3,087:
}
}
}</
{{out}}
Line 2,622 ⟶ 3,107:
=={{header|Sidef}}==
<
var t = 10*floor(n/10)
for k in (t+1 .. t+9 `by` 2) {
Line 2,653 ⟶ 3,138:
say ("First unprimeable that ends with #{d}: ",
1..Inf -> lazy.map {|k| k*10 + d }.grep(is_unprimeable).first)
}</
{{out}}
<pre>
Line 2,675 ⟶ 3,160:
=={{header|Swift}}==
{{trans|Rust}}
<
class BitArray {
Line 2,801 ⟶ 3,286:
let str = NumberFormatter.localizedString(from: number, number: .decimal)
print("Least unprimeable number ending in \(i): \(str)")
}</
{{out}}
Line 2,824 ⟶ 3,309:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<
import "./math" for Int
System.print("The first 35 unprimeable numbers are:")
Line 2,869 ⟶ 3,354:
System.print("The first unprimeable number that ends in:")
for (i in 0...10) System.print(" %(i) is: %(Fmt.dc(9, firstNum[i]))")</
{{out}}
Line 2,889 ⟶ 3,374:
8 is: 208
9 is: 212,159
</pre>
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
func Unprimeable(N); \Return 'true' if N is unprimeable
int N, I, J, Len, D, SD;
char Num(10);
[I:= 0; \take N apart
repeat N:= N/10;
Num(I):= rem(0);
I:= I+1;
until N = 0;
Len:= I; \number of digits in N (length)
for J:= 0 to Len-1 do
[SD:= Num(J); \save digit
for D:= 0 to 9 do \replace with all digits
[Num(J):= D;
N:= 0; \rebuild N
for I:= Len-1 downto 0 do
N:= N*10 + Num(I);
if IsPrime(N) then return false;
];
Num(J):= SD; \restore saved digit
];
return true;
];
int C, N, D;
[Text(0, "First 35 unprimeables:^m^j");
C:= 0;
N:= 100;
loop [if Unprimeable(N) then
[C:= C+1;
if C <= 35 then
[IntOut(0, N); ChOut(0, ^ )];
if C = 600 then quit;
];
N:= N+1;
];
Text(0, "^m^j600th unprimeable: ");
IntOut(0, N); CrLf(0);
for D:= 0 to 9 do
[IntOut(0, D); Text(0, ": ");
N:= 100 + D;
loop [if Unprimeable(N) then
[IntOut(0, N); CrLf(0);
quit;
];
N:= N+10;
];
];
]</syntaxhighlight>
{{out}}
<pre>
First 35 unprimeables:
200 204 206 208 320 322 324 325 326 328 510 512 514 515 516 518 530 532 534 535 536 538 620 622 624 625 626 628 840 842 844 845 846 848 890
600th unprimeable: 5242
0: 200
1: 595631
2: 322
3: 1203623
4: 204
5: 325
6: 206
7: 872897
8: 208
9: 212159
</pre>
Line 2,894 ⟶ 3,457:
{{trans|Sidef}}
{{libheader|GMP}} GNU Multiple Precision Arithmetic Library and fast prime checking
<
fcn isUnprimeable(n){ //--> n (!0) or Void, a filter
Line 2,909 ⟶ 3,472:
n
}
fcn isUnprimeableW{ [100..].tweak(isUnprimeable) } // --> iterator</
<
println("The 600th unprimeable number is: %,d".fmt(isUnprimeableW().drop(600).value));
Line 2,917 ⟶ 3,480:
{ d:=up%10; if(ups[d]==0){ ups[d]=up; if((s-=1)<=0) break; } }
println("The first unprimeable number that ends in:");
foreach n in (10){ println("%d is %8,d".fmt(n,ups[n])) }</
{{out}}
<pre>
|