Truncatable primes: Difference between revisions
Added Uiua solution
(Added Forth solution) |
(Added Uiua solution) |
||
(17 intermediate revisions by 14 users not shown) | |||
Line 23:
* [http://mathworld.wolfram.com/TruncatablePrime.html Truncatable Prime] from MathWorld.]
<br><br>
=={{header|11l}}==
{{trans|C}}
<syntaxhighlight lang="11l">V MAX_PRIME = 1000000
V primes = [1B] * MAX_PRIME
primes[0] = primes[1] = 0B
V i = 2
L i * i < MAX_PRIME
L(j) (i * i .< MAX_PRIME).step(i)
primes[j] = 0B
i++
L i < MAX_PRIME & !primes[i]
i++
F left_trunc(=n)
V tens = 1
L tens < n
tens *= 10
L n != 0
I !:primes[n]
R 0B
tens I/= 10
I n < tens
R 0B
n %= tens
R 1B
F right_trunc(=n)
L n != 0
I !:primes[n]
R 0B
n I/= 10
R 1B
L(n) (MAX_PRIME - 1 .< 0).step(-2)
I left_trunc(n)
print(‘Left: ’n)
L.break
L(n) (MAX_PRIME - 1 .< 0).step(-2)
I right_trunc(n)
print(‘Right: ’n)
L.break</syntaxhighlight>
{{out}}
<pre>
Left: 998443
Right: 739399
</pre>
=={{header|Ada}}==
<syntaxhighlight lang="ada">
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Ordered_Sets;
Line 95 ⟶ 148:
end loop;
end Truncatable_Primes;
</syntaxhighlight>
Sample output:
<pre>
Line 107 ⟶ 160:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<
PROC is prime = (INT n)BOOL:(
Line 162 ⟶ 215:
write("Press Enter");
read(newline)
)</
Output:
<pre>
Line 170 ⟶ 223:
Press Enter
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">leftTruncatable?: function [n][
every? map 0..(size s)-1 'z -> to :integer slice s z (size s)-1
=> prime?
]
rightTruncatable?: function [n][
every? map 0..(size s)-1 'z -> to :integer slice s 0 z
=> prime?
]
upperLimit: 999999
loop range upperLimit .step:2 0 'x [
s: to :string x
if and? not? contains? s "0"
leftTruncatable? x [
print ["highest left-truncatable:" x]
break
]
]
loop range upperLimit .step:2 0 'x [
s: to :string x
if and? not? contains? s "0"
rightTruncatable? x [
print ["highest right-truncatable:" x]
break
]
]</syntaxhighlight>
{{out}}
<pre>highest left-truncatable: 998443
highest right-truncatable: 739399</pre>
=={{header|AutoHotkey}}==
<
MsgBox, % "Largest left-truncatable and right-truncatable primes less than one million:`n"
. "Left:`t" LTP(10 ** 6) "`nRight:`t" RTP(10 ** 6)
Line 227 ⟶ 317:
return, 1
}
}</
'''Output:'''
<pre>Largest left-truncatable and right-truncatable primes less than one million:
Line 234 ⟶ 324:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f TRUNCATABLE_PRIMES.AWK
BEGIN {
Line 285 ⟶ 375:
}
function max(x,y) { return((x > y) ? x : y) }
</syntaxhighlight>
{{out}}
<pre>
Line 295 ⟶ 385:
=={{header|Bracmat}}==
Primality test: In an attempt to compute the result of taking a (not too big, 2^32 or 2^64, depending on word size) number to a fractional power, Bracmat computes the prime factors of the number and checks whether the powers of prime factors make the fractional power go away. If the number is prime, the output of the computation is the same as the input.
<
& whl
' ( !i+-2:>0:?i
Line 311 ⟶ 401:
)
& out$("right:" !i)
)</
Output:
<pre>left: 998443
Line 317 ⟶ 407:
=={{header|C}}==
<
#include <stdlib.h>
#include <string.h>
Line 379 ⟶ 469:
printf("Left: %d; right: %d\n", max_left, max_right);
return 0;
}</
Faster way of doing primality test for small numbers (1000000 isn't big), and generating truncatable primes bottom-up:
<
#define MAXN 1000000
Line 428 ⟶ 518:
return 0;
}</
{{out}}
<pre>
Line 435 ⟶ 525:
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
class truncatable_primes
Line 486 ⟶ 576:
return true;
}
}</
<pre>Output: L 998443 R 739399 24 μs</pre>
=={{header|C++}}==
<
#include "prime_sieve.hpp"
Line 536 ⟶ 626:
std::cout << "Largest right truncatable prime is " << largest_right << '\n';
return 0;
}</
Contents of prime_sieve.hpp:
<
#define PRIME_SIEVE_HPP
Line 590 ⟶ 680:
}
#endif</
{{out}}
Line 599 ⟶ 689:
=={{header|Clojure}}==
<
(def prime?
Line 639 ⟶ 729:
((juxt ffirst (comp second second)) ,)
(map vector ["left truncatable: " "right truncatable: "] ,))
(["left truncatable: " 998443] ["right truncatable: " 739399])</
=={{header|CoffeeScript}}==
<
# truncatable numbers, but they lend themselves to slightly
# different optimizations.
Line 701 ⟶ 791:
console.log "right", max_right_truncatable_number(999999, is_prime)
console.log "left", max_left_truncatable_number(999999, is_prime)
</syntaxhighlight>
output
<syntaxhighlight lang="text">
> coffee truncatable_prime.coffee
right 739399
left 998443
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(defun start ()
(format t "Largest right-truncatable ~a~%" (max-right-truncatable))
Line 752 ⟶ 842:
((zerop (rem n d)) nil)
(t (primep-aux n (+ d 1)))))
</syntaxhighlight>
{{out}}
<pre>Largest right-truncatable 739399
Line 758 ⟶ 848:
=={{header|D}}==
<
std.range;
Line 791 ⟶ 881:
writeln("Largest right-truncatable prime in 2 .. ", n, ": ",
iota(n, 1, -1).filter!(isTruncatablePrime!false).front);
}</
{{out}}
<pre>Largest left-truncatable prime in 2 .. 1000000: 998443
Largest right-truncatable prime in 2 .. 1000000: 739399</pre>
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
<syntaxhighlight lang="Delphi">
procedure TruncatablePrimes(Memo: TMemo);
var Sieve: TPrimeSieve;
var I,P: integer;
function IsLeftTruncatable(P: integer): boolean;
{A prime is Left truncatable, if you can remove digits}
{one at a time from the left and it is still prime}
var S: string;
var P2: integer;
begin
Result:=False;
{Conver number to string}
S:=IntToStr(P);
{Delete one char from the left}
Delete(S,1,1);
while Length(S)>0 do
begin
{Zeros no allowed}
if S[1]='0' then exit;
{Convert back to number}
P2:=StrToInt(S);
{Exit if it is not prime}
if not Sieve.Flags[P2] then exit;
{Delete next char from left}
Delete(S,1,1);
end;
{If all truncated numbers are prime}
Result:=True;
end;
function IsRightTruncatable(P: integer): boolean;
{A prime is right truncatable, if you can remove digits}
{one at a time from the right and it is still prime}
var S: string;
var P2: integer;
begin
Result:=False;
{Conver number to string}
S:=IntToStr(P);
{Delete one char from the right}
Delete(S,Length(S),1);
while Length(S)>0 do
begin
{No zeros allowed}
if S[1]='0' then exit;
{Convert back to number}
P2:=StrToInt(S);
{exit if it is not prime}
if not Sieve.Flags[P2] then exit;
{Delete next char from the right}
Delete(S,Length(S),1);
end;
{If all truncated numbers are prime}
Result:=True;
end;
begin
Sieve:=TPrimeSieve.Create;
try
{Look at primes under 1 million}
Sieve.Intialize(1000000);
{Look for the highest Left Truncatable prime}
{Test all primes from 1 million down}
for I:=Sieve.PrimeCount-1 downto 0 do
begin
P:=Sieve.Primes[I];
{The first number that is Left Truncatable, will be the highest}
if IsLeftTruncatable(P) then
begin
Memo.Lines.Add(IntToStr(P));
break;
end;
end;
{Look for the highest Right Truncatable prime}
{Test all primes from 1 million down}
for I:=Sieve.PrimeCount-1 downto 0 do
begin
P:=Sieve.Primes[I];
if IsRightTruncatable(P) then
begin
Memo.Lines.Add(IntToStr(P));
break;
end;
end;
finally Sieve.Free; end;
end;
</syntaxhighlight>
{{out}}
<pre>
Largest Left Truncatable Prime: 998443
Largest Right Truncatable Prime: 739399
Elapsed Time: 14.666 ms.
</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
fastfunc isprim num .
if num < 2
return 0
.
i = 2
while i <= sqrt num
if num mod i = 0
return 0
.
i += 1
.
return 1
.
func isright h .
while h > 0
if isprim h = 0
return 0
.
h = h div 10
.
return 1
.
func isleft h .
d = pow 10 (floor log10 h)
while h > 0
if isprim h = 0
return 0
.
if h div d = 0
return 0
.
h = h mod d
d /= 10
.
return 1
.
p = 999999
while isleft p = 0
p -= 2
.
print p
p = 999999
while isright p = 0
p -= 2
.
print p
</syntaxhighlight>
{{out}}
<pre>
998443
739399
</pre>
=={{header|EchoLisp}}==
<
;; does p include a 0 in its decimal representation ?
(define (nozero? n) (= -1 (string-index (number->string n) "0")))
Line 814 ⟶ 1,071:
(define (fact-trunc trunc)
(for ((p (in-range 999999 100000 -1))) #:break (when (trunc p) (writeln p) #t)))
</syntaxhighlight>
Output:
<
(fact-trunc left-trunc)
998443
(fact-trunc right-trunc)
739399
</syntaxhighlight>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 975 ⟶ 1,232:
end
</syntaxhighlight>
{{out}}
<pre>
Line 983 ⟶ 1,240:
=={{header|Elena}}==
ELENA
<
const MAXN = 1000000;
Line 996 ⟶ 1,253:
if (n < 2) { ^ false };
if (n < 4) { ^ true };
if (n.mod
if (n < 9) { ^ true };
if (n.mod
int r := n.sqrt();
Line 1,077 ⟶ 1,334:
console.readChar()
}</
{{out}}
<pre>
Line 1,086 ⟶ 1,343:
=={{header|Elixir}}==
{{trans|Ruby}}
<
defp left_truncatable?(n, prime) do
func = fn i when i<=9 -> 0
Line 1,132 ⟶ 1,389:
end
Prime.task</
{{out}}
Line 1,141 ⟶ 1,398:
=={{header|Factor}}==
<syntaxhighlight lang="text">USING: formatting fry grouping.extras kernel literals math
math.parser math.primes sequences ;
IN: rosetta-code.truncatable-primes
Line 1,176 ⟶ 1,433:
"Left: %d\nRight: %d\n" printf ;
MAIN: main</
{{out}}
<pre>
Line 1,185 ⟶ 1,442:
=={{header|Forth}}==
The prime sieve code is borrowed from [[Sieve of Eratosthenes#Forth]].
<
: notprime! ( n -- ) here + 1 swap c! ;
Line 1,209 ⟶ 1,466:
drop false exit
then
dup
10
begin
while
dup
2drop
then
dup prime? invert if
2drop
then
10 *
repeat
2drop
: right_truncatable_prime? ( n -- flag )
Line 1,229 ⟶ 1,487:
drop false exit
then
begin
10 / dup 0 >
while
dup prime? invert if
drop false exit
then
repeat
drop true ;
Line 1,264 ⟶ 1,520:
." Largest right truncatable prime: "
limit max_right_truncatable_prime
bye</syntaxhighlight>
{{out}}
Line 1,274 ⟶ 1,532:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
implicit none
Line 1,361 ⟶ 1,619:
end if
end do
end program</
Output
<pre>Largest left truncatable prime below 1000000 is 998443
Line 1,368 ⟶ 1,626:
=={{header|FreeBASIC}}==
===Version 1===
<
Function isPrime(n As Integer) As Boolean
Line 1,423 ⟶ 1,681:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,432 ⟶ 1,690:
===Version 2===
Construct primes using previous found primes.
<
' compile with: fbc -s console
Line 1,514 ⟶ 1,772:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>
Line 1,521 ⟶ 1,779:
=={{header|Go}}==
<
import "fmt"
Line 1,575 ⟶ 1,833:
}
return false
}</
Output:
<pre>
Line 1,584 ⟶ 1,842:
=={{header|Haskell}}==
Using {{libheader|Primes}} from [http://hackage.haskell.org/packages/hackage.html HackageDB]
<
import Data.List
import Control.Arrow
Line 1,597 ⟶ 1,855:
let (ltp, rtp) = (head. filter leftT &&& head. filter rightT) primes1e6
putStrLn $ "Left truncatable " ++ show ltp
putStrLn $ "Right truncatable " ++ show rtp</
Output:
<
Left truncatable 998443
Right truncatable 739399</
Interpretation of the J contribution:
<
smallPrimes = filter isPrime digits
pow10 = iterate (*10) 1
Line 1,611 ⟶ 1,869:
lefT = liftM2 (.) (+) ((*) . mul10)
primesTruncatable f = iterate (concatMap (filter isPrime.flip map digits. f)) smallPrimes</
Output:
<
739399
*Main> maximum $ primesTruncatable lefT !! 5
998443</
=={{header|Icon}} and {{header|Unicon}}==
<
N := 0 < integer(\arglist[1]) | 1000000 # primes to generator 1 to ... (1M or 1st arglist)
D := (0 < integer(\arglist[2]) | 10) / 2 # primes to display (10 or 2nd arglist)
Line 1,652 ⟶ 1,910:
procedure islefttrunc(P,x) #: return integer x if x and all left truncations of x are in P or fails
if *x = 0 | ( (x := integer(x)) & member(P,x) & islefttrunc(P,x[2:0]) ) then return x
end</
Sample output:<pre>There are 78498 prime numbers in the range 1 to 1000000
Line 1,665 ⟶ 1,923:
In other words, given:
<
seed=: selPrime digits=: 1+i.9
step=: selPrime@,@:(,&.":/&>)@{@;</
Here, selPrime discards non-prime numbers from a list, so seed is the list 2 3 5 7.
Line 1,673 ⟶ 1,931:
The largest truncatable primes less than a million can be obtained by adding five digits to the prime seeds, then finding the largest value from the result.
<
998443
>./ step&digits^:5 seed NB. right truncatable
739399</
Note that we are using the same combining function and same basic procedure in both cases. The difference is which side of the number we add arbitrary digits to, for each step.
=={{header|Java}}==
<
public class Main {
Line 1,750 ⟶ 2,008:
}
}
</syntaxhighlight>
Output :
<pre>
Line 1,756 ⟶ 2,014:
Right Truncatable : 739399
</pre>
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
See [[Erd%C5%91s-primes#jq]] for a suitable implementation of `is_prime` as used here.
<syntaxhighlight lang="jq">def is_left_truncatable_prime:
def removeleft: recurse(if length <= 1 then empty else .[1:] end);
tostring
| index("0") == null and
all(removeleft|tonumber; is_prime);
def is_right_truncatable_prime:
def removeright: recurse(if length <= 1 then empty else .[:-1] end);
tostring
| index("0") == null and
all(removeright|tonumber; is_prime);
first( range(999999; 1; -2) | select(is_left_truncatable_prime)),
first( range(999999; 1; -2) | select(is_right_truncatable_prime))</syntaxhighlight>
{{out}}
<pre>
998443
739399
</pre>
=={{header|Julia}}==
There are several features of Julia that make solving this task easy. Julia has excellent built-in support for prime generation and testing. The built-in mathematical functions <tt>prevpow</tt> and <tt>divrem</tt> are quite handy for implementing <tt>isltruncprime</tt>.
<syntaxhighlight lang="julia">
function isltruncprime{T<:Integer}(n::T, base::T=10)
isprime(n) || return false
Line 1,796 ⟶ 2,081:
break
end
</syntaxhighlight>
{{out}}
Line 1,806 ⟶ 2,091:
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<
fun isPrime(n: Int) : Boolean {
Line 1,863 ⟶ 2,148:
println("Largest left truncatable prime : " + lMax.toString())
println("Largest right truncatable prime : " + rMax.toString())
}</
{{out}}
Line 1,872 ⟶ 2,157:
=={{header|Lua}}==
<
numbers = {}
Line 1,918 ⟶ 2,203:
print( "max_prime_left = ", max_prime_left )
print( "max_prime_right = ", max_prime_right )</
=={{header|Maple}}==
<syntaxhighlight lang="maple">
MaxTruncatablePrime := proc({left::truefalse:=FAIL, right::truefalse:=FAIL}, $)
local i, j, c, p, b, n, sdprimes, dir;
Line 1,971 ⟶ 2,256:
end do;
return max(indices(tprimes, 'nolist'));
end proc;</
<pre>
Line 1,979 ⟶ 2,264:
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
And @@ PrimeQ /@ ToExpression /@ StringJoin /@
Rest[Most[NestList[Rest, #, Length[#]] &[Characters[ToString[n]]]]]
RightTruncatablePrimeQ[n_] := Times @@ IntegerDigits[n] > 0 &&
And @@ PrimeQ /@ ToExpression /@ StringJoin /@
Rest[Most[NestList[Most, #, Length[#]] &[Characters[ToString[n]]]]]</
Example usage:
<pre>n = PrimePi[1000000]; While[Not[LeftTruncatablePrimeQ[Prime[n]]], n--]; Prime[n]
-> 998443
n = PrimePi[1000000]; While[Not[RightTruncatablePrimeQ[Prime[n]]], n--]; Prime[n]
-> 739399</pre>
Line 1,995 ⟶ 2,279:
=={{header|MATLAB}}==
largestTruncatablePrimes.m:
<
%Helper function for checking if a prime is left of right truncatable
Line 2,056 ⟶ 2,340:
end
end
</syntaxhighlight>
Solution for n = 1,000,000:
<syntaxhighlight lang="matlab">
>> largestTruncatablePrimes(1e6)
998443 is the largest left truncatable prime <= 1000000.
739399 is the largest right truncatable prime <= 1000000.
</syntaxhighlight>
=={{header|Nim}}==
{{trans|Python}}
<
proc primes(n: int64): seq[int64] =
var multiples: HashSet[int64]
for i in 2..n:
if i notin multiples:
Line 2,077 ⟶ 2,360:
for j in countup(i*i, n, i.int):
multiples.incl j
proc truncatablePrime(n: int64): tuple[left
var
primelist: seq[string
for x in primes(n):
primelist.add($x)
reverse primelist
var primeset =
for n in primelist:
var alltruncs:
for i in 0..n.
alltruncs.incl n[i..n.high]
if alltruncs <= primeset:
Line 2,093 ⟶ 2,376:
break
for n in primelist:
var alltruncs:
for i in 0..n.
alltruncs.incl n[0..i]
if alltruncs <= primeset:
result.right = parseInt(n)
break
echo truncatablePrime(1000000i64)</syntaxhighlight>
{{out}}
<pre>(left: 998443, right: 739399)</pre>
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
-- find largest left- & right-truncatable primes < 1 million.
-- an initial set of primes (not, at this time, we leave out 2 because
Line 2,171 ⟶ 2,455:
say 'The largest right-truncatable prime is' lastRight '(under one million).'
</syntaxhighlight>
Output:
<pre>
Line 2,181 ⟶ 2,465:
=={{header|OpenEdge/Progress}}==
<
i_i AS INT
):
Line 2,262 ⟶ 2,546:
getHighestTruncatablePrimes( 1000000 )
VIEW-AS ALERT-BOX.
</
Output:
<pre>---------------------------
Line 2,275 ⟶ 2,559:
=={{header|PARI/GP}}==
This version builds the truncatable primes with up to k digits in a straightforward fashion. Run time is about 15 milliseconds, almost all of which is I/O.
<
my(v=[2,3,5,7],u,t=1,out=0);
for(i=1,n,
Line 2,304 ⟶ 2,588:
out
};
[left(6),right(6)]</
=={{header|Perl}}==
Typically with Perl we'll look for a CPAN module to make our life easier. This basically just follows the task rules:
{{libheader|ntheory}}
<
sub isltrunc {
my $n = shift;
Line 2,323 ⟶ 2,607:
for (reverse @{primes(1e6)}) {
if (isrtrunc($_)) { print "rtrunc: $_\n"; last; }
}</
{{out}}
<pre>ltrunc: 998443
rtrunc: 739399</pre>
We can be a little more Perlish and build up n-digit lists then select the last one:
<
my @lprimes = my @rprimes = (2,3,5,7);
Line 2,340 ⟶ 2,624:
for 2..6;
print "ltrunc: $lprimes[-1]\nrtrunc: $rprimes[-1]\n";</
Or we can do everything ourselves:
<
use warnings;
use strict;
Line 2,397 ⟶ 2,681:
}
print 'left ', join(', right ', @tprimes), "\n";</
{{out}}
<pre>left 998443, right 739399</pre>
Line 2,403 ⟶ 2,687:
=={{header|Phix}}==
A slightly different approach. Works up to N=8, quite fast - 10^8 in 5s with ~90% of time spent creating the basic sieve and ~10% propagation and final scan.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">N</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">limit</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- standard sieve:</span>
<span style="color: #008080;">enum</span> <span style="color: #000000;">L</span><span style="color: #0000FF;">,</span><span style="color: #000000;">R</span> <span style="color: #000080;font-style:italic;">-- (with primes[i] as mini bit-field)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">primes</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">L</span><span style="color: #0000FF;">+</span><span style="color: #000000;">R</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">primes</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: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">i</span><span style="color: #0000FF;">*</span><span style="color: #000000;">i</span> <span style="color: #008080;">to</span> <span style="color: #000000;">limit</span> <span style="color: #008080;">by</span> <span style="color: #000000;">i</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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: #000080;font-style:italic;">-- propagate non-truncateables up the prime table:</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">N</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">p10</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- ie 10, 100, .. 100_000</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">p10</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">p10</span><span style="color: #0000FF;">*</span><span style="color: #000000;">10</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- to 99, 999, .. 999_999</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">primes</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: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p10</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">/</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">pi</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">l</span><span style="color: #0000FF;">],</span><span style="color: #000000;">L</span><span style="color: #0000FF;">)+</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">r</span><span style="color: #0000FF;">],</span><span style="color: #000000;">R</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">pi</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sprint</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: #000000;">pi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">pi</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;">end</span> <span style="color: #008080;">for</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">maxl</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">maxr</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">pi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">pi</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">maxl</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">,</span><span style="color: #000000;">L</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">maxl</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">maxr</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">,</span><span style="color: #000000;">R</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">maxr</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">maxl</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #000000;">maxr</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</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: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?{</span><span style="color: #000000;">maxl</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxr</span><span style="color: #0000FF;">}</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 2,447 ⟶ 2,734:
=={{header|PicoLisp}}==
<
(de truncatablePrime? (N Fun)
Line 2,458 ⟶ 2,745:
(until (truncatablePrime? (dec 'Left) cdr))
(until (truncatablePrime? (dec 'Right) '((L) (cdr (rot L)))))
(cons Left Right) )</
Output:
<pre>-> (998443 . 739399)</pre>
=={{header|Pike}}==
<
{
while(p) {
Line 2,491 ⟶ 2,778:
break;
}
}</
Output:
<pre>
Line 2,499 ⟶ 2,786:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
tp: procedure options (main);
declare primes(1000000) bit (1);
Line 2,567 ⟶ 2,854:
end tp;
</syntaxhighlight>
<pre>
739399 is right-truncatable
Line 2,574 ⟶ 2,861:
=={{header|PowerShell}}==
<
{
$isprime = @{}
Line 2,624 ⟶ 2,911:
"Largest Right Truncatable Prime: $lastrtprime"
}
}</
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<
is_left_truncatable_prime(N),
!.
Line 2,671 ⟶ 2,958:
main:-
main(1000000).</
Module for finding prime numbers up to some limit:
<
:- dynamic is_prime/1.
Line 2,715 ⟶ 3,002:
cross_out(S, N, P):-
Q is S + 2 * P,
cross_out(Q, N, P).</
{{out}}
Line 2,724 ⟶ 3,011:
=={{header|PureBasic}}==
<
Procedure is_Prime(n)
Line 2,791 ⟶ 3,078:
y.s="Largest TruncateRight= "+Str(truncateright)
MessageRequester("Truncatable primes",x+#CRLF$+y)</
=={{header|Python}}==
<
def primes(n):
Line 2,823 ⟶ 3,110:
return truncateleft, truncateright
print(truncatableprime(maxprime))</
'''Sample Output'''
<pre>(998443, 739399)</pre>
=={{header|Quackery}}==
<code>eratosthenes</code> and <code>sieve</code> are defined at [[Sieve of Eratosthenes#Quackery]].
<syntaxhighlight lang="quackery"> 1000000 eratosthenes
[ false swap
number$ witheach
[ char 0 =
if [ conclude not ] ] ] is haszero ( n --> b )
[ 10 / ] is truncright ( n --> n )
[ number$
behead drop $->n drop ] is truncleft ( n --> n )
[ dup isprime not iff
[ drop false ] done
dup haszero iff
[ drop false ] done
true swap
[ truncleft
dup 0 > while
dup isprime not iff
[ dip not ] done
again ] drop ] is ltruncatable ( n --> b )
[ dup isprime not iff
[ drop false ] done
dup haszero iff
[ drop false ] done
true swap
[ truncright
dup 0 > while
dup isprime not iff
[ dip not ] done
again ] drop ] is rtruncatable ( n --> b )
say "Left: "
1000000 times [ i ltruncatable if [ i echo conclude ] ]
cr
say "Right: "
1000000 times [ i rtruncatable if [ i echo conclude ] ]
cr</syntaxhighlight>
{{out}}
<pre>Left: 998443
Right: 739399
</pre>
=={{header|Racket}}==
<
#lang racket
(require math/number-theory)
Line 2,863 ⟶ 3,201:
998443
739399
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.09}}
<syntaxhighlight lang="raku"
$[ grep { .&is-prime }, ((1..9) X~ @ltp) ]
} ... *;
Line 2,877 ⟶ 3,215:
say "Highest ltp = ", ltp[5][*-1];
say "Highest rtp = ", rtp[5][*-1];</
{{out}}
<pre>Highest ltp: 998443
Line 2,884 ⟶ 3,222:
=={{header|REXX}}==
Extra code was added to the prime number generator as this is the section of the REXX program that consumes the vast majority of the computation time.
<
parse arg hi .; if hi=='' then hi= 1000000 /*Not specified? Then use default of 1m*/
call genP /*generate some primes, about hi ÷ 2 */
Line 2,921 ⟶ 3,259:
#= #+1; @.#= j; s.#= j*j; !.j= 1 /*bump # of Ps; assign next P; P²; P# */
end /*j*/
return</
{{out|output|text= when using the default inputs:}}
<pre>
Line 2,929 ⟶ 3,267:
=={{header|Ring}}==
<
# Project : Truncatable primes
Line 2,983 ⟶ 3,321:
next
return 1
</syntaxhighlight>
Output:
<pre>
Largest left truncatable prime : 998443
Largest right truncatable prime : 739399
</pre>
=={{header|RPL}}==
{{works with|HP|49}}
≪ → trunc
≪ <span style="color:red">1000000</span>
'''DO'''
'''DO''' PREVPRIME '''UNTIL''' DUP →STR <span style="color:red">"0"</span> POS NOT '''END'''
DUP <span style="color:red">1</span> SF
'''DO'''
trunc EVAL
'''IF''' DUP ISPRIME? NOT '''THEN''' <span style="color:red">1</span> CF '''END'''
'''UNTIL''' DUP <span style="color:red">9</span> ≤ <span style="color:red">1</span> FC? OR '''END'''
DROP
'''UNTIL''' <span style="color:red">1</span> FS? '''END'''
≫ ≫ '<span style="color:blue">XTRUNC</span>' STO
≪ →STR TAIL STR→ ≫ <span style="color:blue">XTRUNC</span>
≪ <span style="color:red">10</span> / IP ≫ <span style="color:blue">XTRUNC</span>
{{out}}
<pre>
2: 998443
1: 739399
</pre>
=={{header|Ruby}}==
<
truncatable?(n) {|i| i.to_s[1..-1].to_i}
end
Line 3,013 ⟶ 3,374:
p primes.detect {|p| left_truncatable? p}
p primes.detect {|p| right_truncatable? p}</
returns
Line 3,026 ⟶ 3,387:
=={{header|Rust}}==
<
if n < 2 {
return false;
Line 3,096 ⟶ 3,457:
}
println!("Largest right truncatable prime is {}", largest_right);
}</
{{out}}
Line 3,106 ⟶ 3,467:
=={{header|Scala}}==
This example uses lazily evaluated lists. The functions to determine if a number is a truncatable prime construct a list of truncated numbers and check that all the elements in the list are prime.
<
def main(args: Array[String]): Unit = {
val max = 1000000
Line 3,122 ⟶ 3,483:
def isLeftTruncPrime(num: Int): Boolean = !num.toString.contains('0') && Iterator.unfold(num.toString){str => if(str.nonEmpty) Some((str.toInt, str.tail)) else None}.forall(isPrime)
def isRightTruncPrime(num: Int): Boolean = !num.toString.exists(_.asDigit%2 == 0) && Iterator.unfold(num.toString){str => if(str.nonEmpty) Some((str.toInt, str.init)) else None}.forall(isPrime)
}</
{{out}}
Line 3,129 ⟶ 3,490:
=={{header|Sidef}}==
<
var p = %w(2 3 5 7);
var f = (
Line 3,142 ⟶ 3,503:
say t_prime(5, left: true)
say t_prime(5, left: false)</
{{out}}
<pre>
Line 3,151 ⟶ 3,512:
=={{header|Swift}}==
{{trans|Rust}}
<
if n < 2 {
return false
Line 3,219 ⟶ 3,580:
p -= 1
}
print("Largest right truncatable prime is \(largestRight)")</
{{out}}
Line 3,228 ⟶ 3,589:
=={{header|Tcl}}==
<
# Optimized version of the Sieve-of-Eratosthenes task solution
Line 3,293 ⟶ 3,654:
break
}
}</
Output:
<pre>
Line 3,302 ⟶ 3,663:
searching for largest right-truncatable prime
FOUND:739399
</pre>
=={{header|Uiua}}==
<syntaxhighlight lang="uiua">
Mag ← 6
MaxP ← ⁿ:10⌊÷2Mag
# Pre-calculate primes up to root of largest n
Primes ← ⇌◌⍢(▽≠0◿⊢..⟜(⊂⊢)|>0⧻.):[]⊂2↘1+1×2⇡⌊÷2 MaxP # Build primes
IsPrime ← ⨬(/↧≡(≠0◿)|1)∊:,,Primes
RAdd ← ♭⊞(+×10):1_3_7_9 # Add suffixes
LAdd ← ♭⊞+×ⁿ:10⌈ₙ10⊢,+1⇡9 # Add prefixes
LastTP! ← ⊡¯1⍥(▽⊸≡IsPrime^!)-1Mag 2_3_5_7 # Build and filter
$"Right truncating: _"LastTP!RAdd
$"Left truncating: _"LastTP!LAdd
</syntaxhighlight>
{{out}}
<pre>
"Right truncating: 739399"
"Left truncating: 998443"
</pre>
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
start_time = Now
Line 3,374 ⟶ 3,754:
End If
End Function
</syntaxhighlight>
{{Out}}
Line 3,386 ⟶ 3,766:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<
import "./math" for Int
var limit = 999999
Line 3,427 ⟶ 3,807:
}
i = i - 2
}</
{{out}}
Line 3,437 ⟶ 3,817:
=={{header|XPL0}}==
<
func Prime(P); \Return true if P is a prime number
Line 3,478 ⟶ 3,858:
[IntOut(0, LeftTrunc); CrLf(0);
IntOut(0, RightTrunc); CrLf(0);
]</
Output:
Line 3,488 ⟶ 3,868:
=={{header|zkl}}==
Using [[Extensible prime generator#zkl]] and a one meg bucket of bytes, construct a yes/no lookup table for all primes <= one million (<80,000).
<
var pTable=Data(million+1,Int).fill(0); // actually bytes, all zero
Line 3,502 ⟶ 3,882:
while(ns){ if(not pTable[ns]) return(False); ns=ns[1,*]; }
True
}</
<
"%,d is a right truncatable prime".fmt(_).println();
[million..0,-1].filter1(leftTrunc):
"%,d is a left truncatable prime".fmt(_).println();</
{{out}}
<pre>
|