A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.



Examples

The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.

The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime.

No zeroes are allowed in truncatable primes.



Task

The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied).



Related tasks
 
 Find largest left truncatable prime in a given base
 Sieve of Eratosthenes


See also

 Truncatable Prime from MathWorld.]


' FB 1.05.0 Win64
 
Function isPrime(n As Integer) As Boolean
  If n Mod 2 = 0 Then Return n = 2
  If n Mod 3 = 0 Then Return n = 3
  Dim d As Integer = 5
  While d * d <= n
    If n Mod d = 0 Then Return False
    d += 2
    If n Mod d = 0 Then Return False
    d += 4
  Wend
  Return True
End Function
 
Dim As UInteger i, j, p, pow, lMax = 2, rMax = 2 
Dim s As String
 
' largest left truncatable prime less than 1000000
' It can't end with 1, 4, 6, 8 or 9 as these numbers are not prime
' Nor can it end in 2 if it has more than one digit as such a number would divide by 2
For i = 3 To 999997 Step 2
  s = Str(i)
  If Instr(s, "0") > 1 Then Continue For '' cannot contain 0   
  j = s[Len(s) - 1] - 48
  If j = 1 OrElse j = 9 Then Continue For
  p = i
  pow = 10 ^ (Len(s) - 1)
  While pow > 1
    If Not isPrime(p) Then Continue For
    p Mod= pow
    pow \= 10
  Wend
  lMax = i
Next
 
' largest right truncatable prime less than 1000000
' It can't begin with 1, 4, 6, 8 or 9 as these numbers are not prime
For i = 3 To 799999 Step 2
  s = Str(i)
  If Instr(s, "0") > 1 Then Continue For '' cannot contain 0   
  j = s[0] - 48
  If j = 1 OrElse j = 4 OrElse j = 6 Then Continue For
  p = i
  While p > 0 
    If Not isPrime(p) Then Continue For  
    p \= 10
  Wend
  rMax = i
Next
 
Print "Largest left  truncatable prime : "; lMax
Print "Largest right truncatable prime : "; rMax
Print
Print "Press any key to quit"
Sleep