Truncatable primes: Difference between revisions

Added Easylang
(Added Pike implementation)
(Added Easylang)
 
(42 intermediate revisions by 16 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">
<lang Ada>
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Ordered_Sets;
Line 95 ⟶ 148:
end loop;
end Truncatable_Primes;
</syntaxhighlight>
</lang>
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''.}}
<langsyntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
 
PROC is prime = (INT n)BOOL:(
Line 162 ⟶ 215:
write("Press Enter");
read(newline)
)</langsyntaxhighlight>
Output:
<pre>
Line 173 ⟶ 226:
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">leftTruncatable?: function [n][
<lang arturo>leftTrunc: @(num){
every? map 0..(size s)-1 'z -> to :integer slice s z (size s)-1
str: toString num
=> prime?
ret: #()
]
loop [range 0 [size str]-1] @(x){
ret: ret + [slice str x [size str]]
}
return [map ret => toNumber]
}
 
rightTruncatable?: function [n][
rightTrunc: @(num){
every? map 0..(size s)-1 'z -> to :integer slice s 0 z
str: toString num
=> prime?
ret: #()
]
loop [size str]..1 @(x){
ret: ret + [slice str 0 x]
}
return [map ret => toNumber]
}
 
upperLimit: 999999
isTruncatablePrime: @(nums)-> all nums => isPrime
 
loop range upperLimit .step:2 0 'x [
MaxLeft: 0
s: to :string x
MaxRight: 0
if and? not? contains? s "0"
 
leftTruncatable? x [
loop [rangeBy 3 1000000 2] @(n){
print ["highest left-truncatable:" x]
if [isTruncatablePrime [leftTrunc n]] -> MaxLeft: n
break
if [isTruncatablePrime [rightTrunc n]] -> MaxRight: n
]
}
]
 
loop range upperLimit .step:2 0 'x [
print "Max Left-Truncatable Prime found (<1000000): " + MaxLeft
s: to :string x
print "Max Right-Truncatable Prime found (<1000000): " + MaxRight</lang>
if and? not? contains? s "0"
rightTruncatable? x [
print ["highest right-truncatable:" x]
break
]
]</syntaxhighlight>
 
{{out}}
 
<pre>Maxhighest Leftleft-Truncatable Prime found (<1000000)truncatable: 998443
Maxhighest Rightright-Truncatable Prime found (<1000000)truncatable: 739399</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">SetBatchLines, -1
MsgBox, % "Largest left-truncatable and right-truncatable primes less than one million:`n"
. "Left:`t" LTP(10 ** 6) "`nRight:`t" RTP(10 ** 6)
Line 265 ⟶ 317:
return, 1
}
}</langsyntaxhighlight>
'''Output:'''
<pre>Largest left-truncatable and right-truncatable primes less than one million:
Left: 998443
Right: 739399</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f TRUNCATABLE_PRIMES.AWK
BEGIN {
Line 322 ⟶ 375:
}
function max(x,y) { return((x > y) ? x : y) }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 332 ⟶ 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.
<langsyntaxhighlight lang="bracmat">( 1000001:?i
& whl
' ( !i+-2:>0:?i
Line 348 ⟶ 401:
)
& out$("right:" !i)
)</langsyntaxhighlight>
Output:
<pre>left: 998443
Line 354 ⟶ 407:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 416 ⟶ 469:
printf("Left: %d; right: %d\n", max_left, max_right);
return 0;
}</langsyntaxhighlight>output<syntaxhighlight lang="text">Left: 998443; right: 739399</langsyntaxhighlight>
 
Faster way of doing primality test for small numbers (1000000 isn't big), and generating truncatable primes bottom-up:
<langsyntaxhighlight lang="c">#include <stdio.h>
 
#define MAXN 1000000
Line 465 ⟶ 518:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 472 ⟶ 525:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System; // 4790@3.6
using System.Collections.Generic;
class truncatable_primes
Line 523 ⟶ 576:
return true;
}
}</langsyntaxhighlight>
<pre>Output: L 998443 R 739399 24 μs</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include "prime_sieve.hpp"
 
bool is_left_truncatable(const prime_sieve& sieve, int p) {
for (int n = 10, q = p; p > n; n *= 10) {
if (!sieve.is_prime(p % n) || q == p % n)
return false;
q = p % n;
}
return true;
}
 
bool is_right_truncatable(const prime_sieve& sieve, int p) {
for (int q = p/10; q > 0; q /= 10) {
if (!sieve.is_prime(q))
return false;
}
return true;
}
 
int main() {
const int limit = 1000000;
 
// find the prime numbers up to the limit
prime_sieve sieve(limit + 1);
 
int largest_left = 0;
int largest_right = 0;
// find largest left truncatable prime
for (int p = limit; p >= 2; --p) {
if (sieve.is_prime(p) && is_left_truncatable(sieve, p)) {
largest_left = p;
break;
}
}
// find largest right truncatable prime
for (int p = limit; p >= 2; --p) {
if (sieve.is_prime(p) && is_right_truncatable(sieve, p)) {
largest_right = p;
break;
}
}
// write results to standard output
std::cout << "Largest left truncatable prime is " << largest_left << '\n';
std::cout << "Largest right truncatable prime is " << largest_right << '\n';
return 0;
}</syntaxhighlight>
 
Contents of prime_sieve.hpp:
<syntaxhighlight lang="cpp">#ifndef PRIME_SIEVE_HPP
#define PRIME_SIEVE_HPP
 
#include <algorithm>
#include <vector>
 
/**
* A simple implementation of the Sieve of Eratosthenes.
* See https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes.
*/
class prime_sieve {
public:
explicit prime_sieve(size_t);
bool is_prime(size_t) const;
private:
std::vector<bool> is_prime_;
};
 
/**
* Constructs a sieve with the given limit.
*
* @param limit the maximum integer that can be tested for primality
*/
inline prime_sieve::prime_sieve(size_t limit) {
limit = std::max(size_t(3), limit);
is_prime_.resize(limit/2, true);
for (size_t p = 3; p * p <= limit; p += 2) {
if (is_prime_[p/2 - 1]) {
size_t inc = 2 * p;
for (size_t q = p * p; q <= limit; q += inc)
is_prime_[q/2 - 1] = false;
}
}
}
 
/**
* Returns true if the given integer is a prime number. The integer
* must be less than or equal to the limit passed to the constructor.
*
* @param n an integer less than or equal to the limit passed to the
* constructor
* @return true if the integer is prime
*/
inline bool prime_sieve::is_prime(size_t n) const {
if (n == 2)
return true;
if (n < 2 || n % 2 == 0)
return false;
return is_prime_.at(n/2 - 1);
}
 
#endif</syntaxhighlight>
 
{{out}}
<pre>
Largest left truncatable prime is 998443
Largest right truncatable prime is 739399
</pre>
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">(use '[clojure.contrib.lazy-seqs :only [primes]])
 
(def prime?
Line 567 ⟶ 729:
((juxt ffirst (comp second second)) ,)
(map vector ["left truncatable: " "right truncatable: "] ,))
(["left truncatable: " 998443] ["right truncatable: " 739399])</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript"># You could have symmetric algorithms for max right and left
# truncatable numbers, but they lend themselves to slightly
# different optimizations.
Line 629 ⟶ 791:
console.log "right", max_right_truncatable_number(999999, is_prime)
console.log "left", max_left_truncatable_number(999999, is_prime)
</syntaxhighlight>
</lang>
output
<syntaxhighlight lang="text">
> coffee truncatable_prime.coffee
right 739399
left 998443
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lsip">
(defun start ()
(format t "Largest right-truncatable ~a~%" (max-right-truncatable))
Line 680 ⟶ 842:
((zerop (rem n d)) nil)
(t (primep-aux n (+ d 1)))))
</syntaxhighlight>
</lang>
{{out}}
<pre>Largest right-truncatable 739399
Line 686 ⟶ 848:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.string, std.conv, std.algorithm,
std.range;
 
Line 719 ⟶ 881:
writeln("Largest right-truncatable prime in 2 .. ", n, ": ",
iota(n, 1, -1).filter!(isTruncatablePrime!false).front);
}</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight lang="lisp">
;; does p include a 0 in its decimal representation ?
(define (nozero? n) (= -1 (string-index (number->string n) "0")))
Line 742 ⟶ 1,071:
(define (fact-trunc trunc)
(for ((p (in-range 999999 100000 -1))) #:break (when (trunc p) (writeln p) #t)))
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="lisp">
(fact-trunc left-trunc)
998443
(fact-trunc right-trunc)
739399
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 903 ⟶ 1,232:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 911 ⟶ 1,240:
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import system'calendarextensions;
import extensions;
 
const MAXN = 1000000;
Line 925 ⟶ 1,253:
if (n < 2) { ^ false };
if (n < 4) { ^ true };
if (n .mod:(2) == 0) { ^ false };
if (n < 9) { ^ true };
if (n .mod:(3) == 0) { ^ false };
int r := n.sqrt();
Line 978 ⟶ 1,306:
}
 
public program()
{
var n := MAXN;
Line 1,004 ⟶ 1,332:
console.printLine("Largest truncable left is ",max_lt);
console.printLine("Largest truncable right is ",max_rt);
}</lang>
console.readChar()
}</syntaxhighlight>
{{out}}
<pre>
Line 1,013 ⟶ 1,343:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Prime do
defp left_truncatable?(n, prime) do
func = fn i when i<=9 -> 0
Line 1,059 ⟶ 1,389:
end
 
Prime.task</langsyntaxhighlight>
 
{{out}}
Line 1,068 ⟶ 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,103 ⟶ 1,433:
"Left: %d\nRight: %d\n" printf ;
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Left: 998443
Right: 739399
</pre>
 
=={{header|Forth}}==
The prime sieve code is borrowed from [[Sieve of Eratosthenes#Forth]].
<syntaxhighlight lang="forth">: prime? ( n -- ? ) here + c@ 0= ;
: notprime! ( n -- ) here + 1 swap c! ;
 
: sieve ( n -- )
here over erase
0 notprime!
1 notprime!
2
begin
2dup dup * >
while
dup prime? if
2dup dup * do
i notprime!
dup +loop
then
1+
repeat
2drop ;
 
: left_truncatable_prime? ( n -- flag )
dup prime? invert if
drop false exit
then
dup >r
10
begin
2dup >
while
2dup mod
dup r> = if
2drop drop false exit
then
dup prime? invert if
2drop drop false exit
then
>r
10 *
repeat
2drop rdrop true ;
 
: right_truncatable_prime? ( n -- flag )
dup prime? invert if
drop false exit
then
begin
10 / dup 0 >
while
dup prime? invert if
drop false exit
then
repeat
drop true ;
 
: max_left_truncatable_prime ( n -- )
begin
dup 0 >
while
dup left_truncatable_prime? if . cr exit then
1-
repeat drop ;
 
: max_right_truncatable_prime ( n -- )
begin
dup 0 >
while
dup right_truncatable_prime? if . cr exit then
1-
repeat drop ;
 
1000000 constant limit
 
limit 1+ sieve
 
." Largest left truncatable prime: "
limit max_left_truncatable_prime
 
." Largest right truncatable prime: "
limit max_right_truncatable_prime
 
bye</syntaxhighlight>
 
{{out}}
<pre>
Largest left truncatable prime: 998443
Largest right truncatable prime: 739399
</pre>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">module primes_mod
implicit none
Line 1,199 ⟶ 1,619:
end if
end do
end program</langsyntaxhighlight>
Output
<pre>Largest left truncatable prime below 1000000 is 998443
Line 1,206 ⟶ 1,626:
=={{header|FreeBASIC}}==
===Version 1===
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function isPrime(n As Integer) As Boolean
Line 1,261 ⟶ 1,681:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,270 ⟶ 1,690:
===Version 2===
Construct primes using previous found primes.
<langsyntaxhighlight lang="freebasic">' version 10-12-2016
' compile with: fbc -s console
 
Line 1,352 ⟶ 1,772:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>
Line 1,359 ⟶ 1,779:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,413 ⟶ 1,833:
}
return false
}</langsyntaxhighlight>
Output:
<pre>
Line 1,422 ⟶ 1,842:
=={{header|Haskell}}==
Using {{libheader|Primes}} from [http://hackage.haskell.org/packages/hackage.html HackageDB]
<langsyntaxhighlight lang="haskell">import Data.Numbers.Primes(primes, isPrime)
import Data.List
import Control.Arrow
Line 1,435 ⟶ 1,855:
let (ltp, rtp) = (head. filter leftT &&& head. filter rightT) primes1e6
putStrLn $ "Left truncatable " ++ show ltp
putStrLn $ "Right truncatable " ++ show rtp</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="haskell">*Main> main
Left truncatable 998443
Right truncatable 739399</langsyntaxhighlight>
 
Interpretation of the J contribution:
<langsyntaxhighlight lang="haskell">digits = [1..9] :: [Integer]
smallPrimes = filter isPrime digits
pow10 = iterate (*10) 1
Line 1,449 ⟶ 1,869:
lefT = liftM2 (.) (+) ((*) . mul10)
 
primesTruncatable f = iterate (concatMap (filter isPrime.flip map digits. f)) smallPrimes</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="haskell">*Main> maximum $ primesTruncatable righT !! 5
739399
 
*Main> maximum $ primesTruncatable lefT !! 5
998443</langsyntaxhighlight>
 
== {{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
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,490 ⟶ 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</langsyntaxhighlight>
 
Sample output:<pre>There are 78498 prime numbers in the range 1 to 1000000
Line 1,497 ⟶ 1,917:
Largest right truncatable prime = 739399</pre>
 
== {{header|J}} ==
 
Truncatable primes may be constructed by starting with a set of one digit prime numbers and then repeatedly adding a non-zero digit (combine all possibilities of a truncatable prime digit sequence with each digit) and, at each step, selecting the prime numbers which result.
Line 1,503 ⟶ 1,923:
In other words, given:
 
<langsyntaxhighlight lang="j">selPrime=: #~ 1&p:
seed=: selPrime digits=: 1+i.9
step=: selPrime@,@:(,&.":/&>)@{@;</langsyntaxhighlight>
 
Here, selPrime discards non-prime numbers from a list, so seed is the list 2 3 5 7.
Line 1,511 ⟶ 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.
 
<langsyntaxhighlight lang="j"> >./ digits&step^:5 seed NB. left truncatable
998443
>./ step&digits^:5 seed NB. right truncatable
739399</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight Javalang="java">import java.util.BitSet;
 
public class Main {
Line 1,588 ⟶ 2,008:
}
}
</syntaxhighlight>
</lang>
Output :
<pre>
Line 1,594 ⟶ 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">
<lang Julia>
function isltruncprime{T<:Integer}(n::T, base::T=10)
isprime(n) || return false
Line 1,634 ⟶ 2,081:
break
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,644 ⟶ 2,091:
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="scala">// version 1.0.5-2
 
fun isPrime(n: Int) : Boolean {
Line 1,701 ⟶ 2,148:
println("Largest left truncatable prime : " + lMax.toString())
println("Largest right truncatable prime : " + rMax.toString())
}</langsyntaxhighlight>
 
{{out}}
Line 1,710 ⟶ 2,157:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">max_number = 1000000
 
numbers = {}
Line 1,756 ⟶ 2,203:
 
print( "max_prime_left = ", max_prime_left )
print( "max_prime_right = ", max_prime_right )</langsyntaxhighlight>
 
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
MaxTruncatablePrime := proc({left::truefalse:=FAIL, right::truefalse:=FAIL}, $)
local i, j, c, p, b, n, sdprimes, dir;
Line 1,810 ⟶ 2,256:
end do;
return max(indices(tprimes, 'nolist'));
end proc;</langsyntaxhighlight>
<pre>
 
Line 1,818 ⟶ 2,264:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
 
<syntaxhighlight lang="mathematica">LeftTruncatablePrimeQ[n_] := Times @@ IntegerDigits[n] > 0 &&
 
=={{header|Mathematica}}==
<lang Mathematica>LeftTruncatablePrimeQ[n_] := Times @@ IntegerDigits[n] > 0 &&
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]]]]]</langsyntaxhighlight>
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,836 ⟶ 2,279:
=={{header|MATLAB}}==
largestTruncatablePrimes.m:
<langsyntaxhighlight MATLABlang="matlab">function largestTruncatablePrimes(boundary)
 
%Helper function for checking if a prime is left of right truncatable
Line 1,897 ⟶ 2,340:
end
end
</syntaxhighlight>
</lang>
Solution for n = 1,000,000:
<syntaxhighlight lang="matlab">
<lang MATLAB>
>> largestTruncatablePrimes(1e6)
998443 is the largest left truncatable prime <= 1000000.
739399 is the largest right truncatable prime <= 1000000.
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
 
{{trans|Python}}
<langsyntaxhighlight lang="nim">import sets, strutils, algorithm
 
proc primes(n: int64): seq[int64] =
var multiples: HashSet[int64]
result = @[]
var multiples = initSet[int64]()
for i in 2..n:
if i notin multiples:
Line 1,918 ⟶ 2,360:
for j in countup(i*i, n, i.int):
multiples.incl j
 
proc truncatablePrime(n: int64): tuple[left: int64, right: int64] =
var
primelist: seq[string] = @[]
for x in primes(n):
primelist.add($x)
reverse primelist
var primeset = toSet primelist.toHashSet
for n in primelist:
var alltruncs: = initSetHashSet[string]()
for i in 0..n.len-1high:
alltruncs.incl n[i..n.high]
if alltruncs <= primeset:
Line 1,934 ⟶ 2,376:
break
for n in primelist:
var alltruncs: = initSetHashSet[string]()
for i in 0..n.len-1high:
alltruncs.incl n[0..i]
if alltruncs <= primeset:
result.right = parseInt(n)
break
echo truncatablePrime(1000000i64)</syntaxhighlight>
 
{{out}}
echo truncatablePrime(1000000'i64)</lang>
Output:
<pre>(left: 998443, right: 739399)</pre>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<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,012 ⟶ 2,455:
say 'The largest right-truncatable prime is' lastRight '(under one million).'
 
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,022 ⟶ 2,465:
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight lang="progress">FUNCTION isPrime RETURNS LOGICAL (
i_i AS INT
):
Line 2,103 ⟶ 2,546:
getHighestTruncatablePrimes( 1000000 )
VIEW-AS ALERT-BOX.
</langsyntaxhighlight>
Output:
<pre>---------------------------
Line 2,116 ⟶ 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.
<langsyntaxhighlight lang="parigp">left(n)={
my(v=[2,3,5,7],u,t=1,out=0);
for(i=1,n,
Line 2,145 ⟶ 2,588:
out
};
[left(6),right(6)]</langsyntaxhighlight>
 
=={{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}}
<langsyntaxhighlight lang="perl">use ntheory ":all";
sub isltrunc {
my $n = shift;
Line 2,164 ⟶ 2,607:
for (reverse @{primes(1e6)}) {
if (isrtrunc($_)) { print "rtrunc: $_\n"; last; }
}</langsyntaxhighlight>
{{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:
<langsyntaxhighlight lang="perl">use ntheory ":all";
 
my @lprimes = my @rprimes = (2,3,5,7);
Line 2,181 ⟶ 2,624:
for 2..6;
 
print "ltrunc: $lprimes[-1]\nrtrunc: $rprimes[-1]\n";</langsyntaxhighlight>
 
Or we can do everything ourselves:
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use warnings;
use strict;
Line 2,238 ⟶ 2,681:
}
 
print 'left ', join(', right ', @tprimes), "\n";</langsyntaxhighlight>
{{out}}
<pre>left 998443, right 739399</pre>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2015.09}}
<lang perl6>constant ltp = $[2, 3, 5, 7], -> @ltp {
$[ grep { .&is-prime }, ((1..9) X~ @ltp) ]
} ... *;
 
constant rtp = $[2, 3, 5, 7], -> @rtp {
$[ grep { .&is-prime }, (@rtp X~ (1..9)) ]
} ... *;
 
say "Highest ltp = ", ltp[5][*-1];
say "Highest rtp = ", rtp[5][*-1];</lang>
{{out}}
<pre>Highest ltp: 998443
Highest rtp: 739399</pre>
 
=={{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)-->
<lang Phix>constant N = 6, limit = power(10,N)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
-- standard sieve:
<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>
enum L,R -- (with primes[i] as mini bit-field)
<span style="color: #000080;font-style:italic;">-- standard sieve:</span>
sequence primes = repeat(L+R, limit)
<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>
primes[1] = 0
<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>
for i=2 to floor(sqrt(limit)) do
<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>
if primes[i] then
<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>
for k=i*i to limit by i do
<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>
primes[k] = 0
<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>
end for
<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>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
-- propagate non-truncateables up the prime table:
for p=1 to N-1 do
<span style="color: #000080;font-style:italic;">-- propagate non-truncateables up the prime table:</span>
integer p10 = power(10,p) -- ie 10, 100, .. 100_000
<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>
for i=p10+1 to p10*10-1 by 2 do -- to 99, 999, .. 999_999
<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>
if primes[i] then
<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>
integer l = remainder(i,p10),
<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>
r = floor(i/10)
<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>
integer pi = and_bits(primes[l],L)+and_bits(primes[r],R)
<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>
if pi and find('0',sprint(i)) then pi = 0 end if
<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>
primes[i] = pi
<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>
end if
<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>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
integer maxl=0, maxr=0
 
<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>
for i=limit-1 to 1 by -2 do
integer pi = primes[i]
<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>
if pi then
<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>
if maxl=0 and and_bits(pi,L) then maxl = i end if
<span style="color: #008080;">if</span> <span style="color: #000000;">pi</span> <span style="color: #008080;">then</span>
if maxr=0 and and_bits(pi,R) then maxr = i end if
<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>
if maxl!=0 and maxr!=0 then exit end if
<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>
end if
<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>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
?{maxl,maxr}</lang>
<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,304 ⟶ 2,734:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/rsa.l") # Use the 'prime?' function from RSA package
 
(de truncatablePrime? (N Fun)
Line 2,315 ⟶ 2,745:
(until (truncatablePrime? (dec 'Left) cdr))
(until (truncatablePrime? (dec 'Right) '((L) (cdr (rot L)))))
(cons Left Right) )</langsyntaxhighlight>
Output:
<pre>-> (998443 . 739399)</pre>
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">bool is_trunc_prime(int p, string direction)
<lang Pike>
array get_primes(int roof)
{
int p = 2;
array primes = ({});
do {
primes += ({ p });
p = p->next_prime();
} while (p < roof);
return primes;
}
 
bool is_prime(int candidate)
{
if( (candidate-1)->next_prime() == candidate )
return true;
return false;
}
 
bool is_lt_prime(int p)
{
while(p) {
if( !is_prime(p->probably_prime_p() )
return false;
if(direction == "l")
p = (int)p->digits()[1..];
p = (int)p->digits()[1..];
}
else
return true;
p = (int)p->digits()[..<1];
}
 
bool is_rt_prime(int p)
{
while(p) {
if( !is_prime(p) )
return false;
p = (int)p->digits()[..<1];
}
return true;
Line 2,361 ⟶ 2,765:
void main()
{
array primes = get_primes( 10->pow(6) );
bool ltp_found, rtp_found;
foreachfor(int reverseprime = 10->pow(primes6),; intprime--; prime > 0) {
if( !ltp_found && is_lt_primeis_trunc_prime(prime, "l") ) {
ltp_found = true;
write("Largest LTP: %d\n", prime);
}
if( !rtp_found && is_rt_primeis_trunc_prime(prime, "r") ) {
rtp_found = true;
write("Largest RTP: %d\n", prime);
Line 2,375 ⟶ 2,778:
break;
}
}</syntaxhighlight>
}
Output:
</lang>
<pre>
Largest LTP: 999907
Largest RTP: 739399
</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
tp: procedure options (main);
declare primes(1000000) bit (1);
Line 2,447 ⟶ 2,854:
 
end tp;
</syntaxhighlight>
</lang>
<pre>
739399 is right-truncatable
Line 2,454 ⟶ 2,861:
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">function IsPrime ( [int] $num )
{
$isprime = @{}
Line 2,504 ⟶ 2,911:
"Largest Right Truncatable Prime: $lastrtprime"
}
}</langsyntaxhighlight>
 
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<syntaxhighlight lang="prolog">largest_left_truncatable_prime(N, N):-
is_left_truncatable_prime(N),
!.
largest_left_truncatable_prime(N, P):-
N > 1,
N1 is N - 1,
largest_left_truncatable_prime(N1, P).
 
is_left_truncatable_prime(P):-
is_prime(P),
is_left_truncatable_prime(P, P, 10).
 
is_left_truncatable_prime(P, _, N):-
P =< N,
!.
is_left_truncatable_prime(P, Q, N):-
Q1 is P mod N,
is_prime(Q1),
Q \= Q1,
N1 is N * 10,
is_left_truncatable_prime(P, Q1, N1).
 
largest_right_truncatable_prime(N, N):-
is_right_truncatable_prime(N),
!.
largest_right_truncatable_prime(N, P):-
N > 1,
N1 is N - 1,
largest_right_truncatable_prime(N1, P).
 
is_right_truncatable_prime(P):-
is_prime(P),
Q is P // 10,
(Q == 0, ! ; is_right_truncatable_prime(Q)).
 
main(N):-
find_prime_numbers(N),
largest_left_truncatable_prime(N, L),
writef('Largest left-truncatable prime less than %t: %t\n', [N, L]),
largest_right_truncatable_prime(N, R),
writef('Largest right-truncatable prime less than %t: %t\n', [N, R]).
 
main:-
main(1000000).</syntaxhighlight>
 
Module for finding prime numbers up to some limit:
<syntaxhighlight lang="prolog">:- module(prime_numbers, [find_prime_numbers/1, is_prime/1]).
:- dynamic is_prime/1.
 
find_prime_numbers(N):-
retractall(is_prime(_)),
assertz(is_prime(2)),
init_sieve(N, 3),
sieve(N, 3).
 
init_sieve(N, P):-
P > N,
!.
init_sieve(N, P):-
assertz(is_prime(P)),
Q is P + 2,
init_sieve(N, Q).
 
sieve(N, P):-
P * P > N,
!.
sieve(N, P):-
is_prime(P),
!,
S is P * P,
cross_out(S, N, P),
Q is P + 2,
sieve(N, Q).
sieve(N, P):-
Q is P + 2,
sieve(N, Q).
 
cross_out(S, N, _):-
S > N,
!.
cross_out(S, N, P):-
retract(is_prime(S)),
!,
Q is S + 2 * P,
cross_out(Q, N, P).
cross_out(S, N, P):-
Q is S + 2 * P,
cross_out(Q, N, P).</syntaxhighlight>
 
{{out}}
<pre>
Largest left-truncatable prime less than 1000000: 998443
Largest right-truncatable prime less than 1000000: 739399
</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">#MaxLim = 999999
 
Procedure is_Prime(n)
Line 2,574 ⟶ 3,078:
y.s="Largest TruncateRight= "+Str(truncateright)
 
MessageRequester("Truncatable primes",x+#CRLF$+y)</langsyntaxhighlight>
 
== {{header|Python}} ==
<langsyntaxhighlight lang="python">maxprime = 1000000
 
def primes(n):
Line 2,606 ⟶ 3,110:
return truncateleft, truncateright
 
print(truncatableprime(maxprime))</langsyntaxhighlight>
 
'''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}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
(require math/number-theory)
Line 2,646 ⟶ 3,201:
998443
739399
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.09}}
<syntaxhighlight lang="raku" line>constant ltp = $[2, 3, 5, 7], -> @ltp {
$[ grep { .&is-prime }, ((1..9) X~ @ltp) ]
} ... *;
 
constant rtp = $[2, 3, 5, 7], -> @rtp {
$[ grep { .&is-prime }, (@rtp X~ (1..9)) ]
} ... *;
 
say "Highest ltp = ", ltp[5][*-1];
say "Highest rtp = ", rtp[5][*-1];</syntaxhighlight>
{{out}}
<pre>Highest ltp: 998443
Highest rtp: 739399</pre>
 
=={{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.
<langsyntaxhighlight REXXlang="rexx">/*REXX program finds largest left─ and right─truncatable primes ≤ 1m (or argument 1).*/
parse arg highhi .; if highhi=='' then highhi= 1000000 /*Not specified? Then use default of 1m*/
!.=0;call genP w=length(high) /*placeholdersgenerate forsome primes;, about hi max÷ width.2 */
@.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17 /*define some low primes. */
!.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1 /*set some low prime flags. */
#=7; s.#=@.#**2 /*number of primes so far; prime². */
/* [↓] generate more primes ≤ high.*/
do j=@.#+2 by 2 for max(0, high%2-@.#%2-1) /*only find odd primes from here on out*/
if j// 3==0 then iterate /*is J divisible by three? */
parse var j '' -1 _; if _==5 then iterate /* " " " " five? (right digit)*/
if j// 7==0 then iterate /* " " " " seven? */
if j//11==0 then iterate /* " " " " eleven? */
if j//13==0 then iterate /* " " " " thirteen? */
/* [↑] the above five lines saves time*/
do k=7 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 up to the √ J */
#=#+1 /*bump the number of primes found. */
@.#=j; s.#=j*j; !.j=1 /*assign next prime; prime²; prime #.*/
end /*j*/
/* [↓] find largest left truncatable P*/
do L=# by -1 for #; digs=length(@.L) /*search from top end; get the length.*/
do k=1 for digslength(@.L); _= right(@.L, k) /*validate all left truncatable primes.*/
if \!._ then iterate L /*Truncated number not prime? Skip it.*/
end /*k*/
leave /*egress, found left truncatable prime.*/
end /*L*/
/* [↓] find largest right truncated P.*/
do R=# by -1 for #; digs=length(@.R) /*search from top end; get the length.*/
do k=1 for digslength(@.R); _= left(@.R, k) /*validate all right truncatable primes*/
if \!._ then iterate R /*Truncated number not prime? Skip it.*/
end /*k*/
leave /*egress, found right truncatable prime*/
end /*R*/
 
/* [↓] show largest left/right trunc P*/
say 'The lastlargest prime foundleft─truncatable isprime ' @.# " (therehi are" # 'primes ≤'" is high") right(@."L, w)
say copies('─',The 70)largest right─truncatable prime ≤' hi " is " right(@.R, /*show a separator line for the output.*/w)
sayexit 'The largest left─truncatable prime ≤' high " is " right(@.L /*stick a fork in it, w) we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
say 'The largest right─truncatable prime ≤' high " is " right(@.R, w)
genP: !.= 0; w= length(hi) /*stickplaceholders afor forkprimes; in it,max we're all donewidth. */</lang>
@.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */
'''output''' &nbsp; when using the default input:
!.2=1; !.3=1; !.5=1; !.7=1; !.11=1 /* " " " " flags. */
#=5; s.#= @.# **2 /*number of primes so far; prime². */
/* [↓] generate more primes ≤ high.*/
do j=@.#+2 by 2 for max(0, hi%2-@.#%2-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? */
if j// 7==0 then iterate /*" " " 7? */
/* [↑] the above five lines saves time*/
do k=5 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; !.j= 1 /*bump # of Ps; assign next P; P²; P# */
end /*j*/
return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
The last prime found is 999983 (there are 78498 primes ≤ 1000000).
──────────────────────────────────────────────────────────────────────
The largest left─truncatable prime ≤ 1000000 is 998443
The largest right─truncatable prime ≤ 1000000 is 739399
Line 2,699 ⟶ 3,267:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Truncatable primes
 
Line 2,753 ⟶ 3,321:
next
return 1
</syntaxhighlight>
</lang>
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}}==
<langsyntaxhighlight lang="ruby">def left_truncatable?(n)
truncatable?(n) {|i| i.to_s[1..-1].to_i}
end
Line 2,783 ⟶ 3,374:
 
p primes.detect {|p| left_truncatable? p}
p primes.detect {|p| right_truncatable? p}</langsyntaxhighlight>
 
returns
Line 2,793 ⟶ 3,384:
<pre>
The largest left truncatable prime less than 1000000 in base 10 is 998443
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
if n % 2 == 0 {
return n == 2;
}
if n % 3 == 0 {
return n == 3;
}
let mut p = 5;
while p * p <= n {
if n % p == 0 {
return false;
}
p += 2;
if n % p == 0 {
return false;
}
p += 4;
}
true
}
 
fn is_left_truncatable(p: u32) -> bool {
let mut n = 10;
let mut q = p;
while p > n {
if !is_prime(p % n) || q == p % n {
return false;
}
q = p % n;
n *= 10;
}
true
}
 
fn is_right_truncatable(p: u32) -> bool {
let mut q = p / 10;
while q > 0 {
if !is_prime(q) {
return false;
}
q /= 10;
}
true
}
 
fn main() {
let limit = 1000000;
let mut largest_left = 0;
let mut largest_right = 0;
let mut p = limit;
while p >= 2 {
if is_prime(p) && is_left_truncatable(p) {
largest_left = p;
break;
}
p -= 1;
}
println!("Largest left truncatable prime is {}", largest_left);
p = limit;
while p >= 2 {
if is_prime(p) && is_right_truncatable(p) {
largest_right = p;
break;
}
p -= 1;
}
println!("Largest right truncatable prime is {}", largest_right);
}</syntaxhighlight>
 
{{out}}
<pre>
Largest left truncatable prime is 998443
Largest right truncatable prime is 739399
</pre>
 
=={{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.
<langsyntaxhighlight lang="scala">object TruncatablePrimes {
def main(args: Array[String]): Unit = {
val max = 1000000
Line 2,813 ⟶ 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)
}</langsyntaxhighlight>
 
{{out}}
Line 2,820 ⟶ 3,490:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func t_prime(n, left=true) {
var p = %w(2 3 5 7);
var f = (
Line 2,833 ⟶ 3,503:
 
say t_prime(5, left: true)
say t_prime(5, left: false)</langsyntaxhighlight>
{{out}}
<pre>
998443
739399
</pre>
 
=={{header|Swift}}==
{{trans|Rust}}
<syntaxhighlight lang="swift">func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
if n % 2 == 0 {
return n == 2
}
if n % 3 == 0 {
return n == 3
}
var p = 5
while p * p <= n {
if n % p == 0 {
return false
}
p += 2
if n % p == 0 {
return false
}
p += 4
}
return true
}
 
func isLeftTruncatable(_ p: Int) -> Bool {
var n = 10
var q = p
while p > n {
if !isPrime(p % n) || q == p % n {
return false
}
q = p % n
n *= 10
}
return true
}
 
func isRightTruncatable(_ p: Int) -> Bool {
var q = p / 10
while q > 0 {
if !isPrime(q) {
return false
}
q /= 10
}
return true
}
 
let limit = 1000000
var largestLeft = 0
var largestRight = 0
var p = limit
while p >= 2 {
if isPrime(p) && isLeftTruncatable(p) {
largestLeft = p
break
}
p -= 1
}
print("Largest left truncatable prime is \(largestLeft)")
p = limit
while p >= 2 {
if isPrime(p) && isRightTruncatable(p) {
largestRight = p
break
}
p -= 1
}
print("Largest right truncatable prime is \(largestRight)")</syntaxhighlight>
 
{{out}}
<pre>
Largest left truncatable prime is 998443
Largest right truncatable prime is 739399
</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
# Optimized version of the Sieve-of-Eratosthenes task solution
Line 2,906 ⟶ 3,654:
break
}
}</langsyntaxhighlight>
Output:
<pre>
Line 2,918 ⟶ 3,666:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
start_time = Now
 
Line 2,987 ⟶ 3,735:
End If
End Function
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,994 ⟶ 3,742:
Largest RTP from 1..1000000: 739399
Elapse Time(seconds) : 49
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
import "./math" for Int
 
var limit = 999999
var c = Int.primeSieve(limit, false)
var leftFound = false
var rightFound = false
System.print("Largest truncatable primes less than a million:")
var i = limit
while (i > 2) {
if (!c[i]) {
if (!rightFound) {
var p = (i/10).floor
while (p > 0) {
if (p%2 == 0 || c[p]) break
p = (p/10).floor
}
if (p == 0) {
System.print(" Right truncatable prime = %(Fmt.dc(0, i))")
rightFound = true
if (leftFound) return
}
}
if (!leftFound) {
var q = i.toString[1..-1]
if (!q.contains("0")) {
var p = Num.fromString(q)
while (q.count > 0) {
if (p%2 == 0 || c[p]) break
q = q[1..-1]
p = Num.fromString(q)
}
if (q == "") {
System.print(" Left truncatable prime = %(Fmt.dc(0, i))")
leftFound = true
if (rightFound) return
}
}
}
}
i = i - 2
}</syntaxhighlight>
 
{{out}}
<pre>
Largest truncatable primes less than a million:
Left truncatable prime = 998,443
Right truncatable prime = 739,399
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code CrLf=9, IntOut=11;
 
func Prime(P); \Return true if P is a prime number
Line 3,038 ⟶ 3,839:
[IntOut(0, LeftTrunc); CrLf(0);
IntOut(0, RightTrunc); CrLf(0);
]</langsyntaxhighlight>
 
Output:
Line 3,048 ⟶ 3,849:
=={{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).
<langsyntaxhighlight lang="zkl">const million=0d1_000_000;
 
var pTable=Data(million+1,Int).fill(0); // actually bytes, all zero
Line 3,062 ⟶ 3,863:
while(ns){ if(not pTable[ns]) return(False); ns=ns[1,*]; }
True
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">[million..0,-1].filter1(rightTrunc):
"%,d is a right truncatable prime".fmt(_).println();
[million..0,-1].filter1(leftTrunc):
"%,d is a left truncatable prime".fmt(_).println();</langsyntaxhighlight>
{{out}}
<pre>
1,981

edits