The Wayback Machine - https://web.archive.org/web/20240712040220/https://www.geeksforgeeks.org/left-truncatable-prime/
Open In App

Left-Truncatable Prime

Last Updated : 23 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A Left-truncatable prime is a prime which in a given base (say 10) does not contain 0 and which remains prime when the leading (“left”) digit is successively removed. For example, 317 is left-truncatable prime since 317, 17 and 7 are all prime. There are total 4260 left-truncatable primes.
The task is to check whether the given number (N >0) is left-truncatable prime or not.

Examples: 

Input: 317
Output: Yes

Input: 293
Output: No
293 is not left-truncatable prime because 
numbers formed are 293, 93 and 3. Here, 293 
and 3 are prime but 93 is not prime.

The idea is to first check whether the number contains 0 as a digit or not and count number of digits in the given number N. If it contains 0, then return false otherwise generate all the primes less than or equal to the given number N using Sieve of Eratosthenes.. Once we have generated all such primes, then we check whether the number remains prime when the leading (“left”) digit is successively removed.

Below is the implementation of the above approach.

C++




// Program to check whether a given number
// is left-truncatable prime or not.
#include<bits/stdc++.h>
using namespace std;
 
/* Function to calculate x raised to the power y */
int power(int x, unsigned int y)
{
    if (y == 0)
        return 1;
    else if (y%2 == 0)
        return power(x, y/2)*power(x, y/2);
    else
        return x*power(x, y/2)*power(x, y/2);
}
 
// Generate all prime numbers less than n.
bool sieveOfEratosthenes(int n, bool isPrime[])
{
    // Initialize all entries of boolean array
    // as true. A value in isPrime[i] will finally
    // be false if i is Not a prime, else true
    // bool isPrime[n+1];
    isPrime[0] = isPrime[1] = false;
    for (int i=2; i<=n; i++)
        isPrime[i] = true;
 
    for (int p=2; p*p<=n; p++)
    {
        // If isPrime[p] is not changed, then it is
        // a prime
        if (isPrime[p] == true)
        {
            // Update all multiples of p
            for (int i=p*2; i<=n; i += p)
                isPrime[i] = false;
        }
    }
}
 
// Returns true if n is right-truncatable, else false
bool leftTruPrime(int n)
{
    int temp = n, cnt = 0, temp1;
 
    // Counting number of digits in the
    // input number and checking whether it
    // contains 0 as digit or not.
    while (temp)
    {
        cnt++; // counting number of digits.
 
        temp1 = temp%10; // checking whether digit is 0 or not
        if (temp1==0)
            return false; // if digit is 0, return false.
        temp = temp/10;
    }
 
    // Generating primes using Sieve
    bool isPrime[n+1];
    sieveOfEratosthenes(n, isPrime);
 
    // Checking whether the number remains prime
    // when the leading ("left") digit is successively
    // removed
    for (int i=cnt; i>0; i--)
    {
        // Checking number by successively removing
        // leading ("left") digit.
        /* n=113, cnt=3
        i=3 mod=1000 n%mod=113
        i=2 mod=100 n%mod=13
        i=3 mod=10 n%mod=3 */
        int mod=  power(10,i);
 
        if (!isPrime[n%mod]) // checking prime
            return false; // if not prime, return false
    }
    return true; // if remains prime, return true
}
 
// Driver program
int main()
{
    int n = 113;
 
    if (leftTruPrime(n))
        cout << n << " is left truncatable prime" << endl;
    else
        cout << n << " is not left truncatable prime" << endl;
    return 0;
}


Java




// Program to check whether
// a given number is left
// truncatable prime or not.
import java.io.*;
 
class GFG {
         
    // Function to calculate x
    // raised to the power y
    static int power(int x,int y)
    {
        if (y == 0)
            return 1;
        else if (y%2 == 0)
            return power(x, y/2)
                   *power(x, y/2);
        else
            return x*power(x, y/2)
                   *power(x, y/2);
    }
      
    // Generate all prime
    // numbers less than n.
    static void sieveOfEratosthenes
                (int n, boolean isPrime[])
    {
         
        // Initialize all entries of boolean
        // array as true. A value in isPrime[i]
        // will finally be false if i is Not
        // a prime, else true bool isPrime[n+1];
        isPrime[0] = isPrime[1] = false;
        for (int i = 2; i <= n; i++)
            isPrime[i] = true;
      
        for (int p = 2; p*p <= n; p++)
        {
            // If isPrime[p] is not changed,
            // then it is a prime
            if (isPrime[p] == true)
            {
                 
                // Update all multiples of p
                for (int i = p*2; i <= n; i += p)
                    isPrime[i] = false;
            }
        }
    }
      
    // Returns true if n is
    // right-truncatable, else false
    static boolean leftTruPrime(int n)
    {
        int temp = n, cnt = 0, temp1;
      
        // Counting number of digits in the
        // input number and checking whether
        // it contains 0 as digit or not.
        while (temp != 0)
        {
            // counting number of digits.
            cnt++;
      
            temp1 = temp%10;
             
            // checking whether digit is
            // 0 or not
            if (temp1 == 0)
                return false;
            temp = temp/10;
        }
      
        // Generating primes using Sieve
        boolean isPrime[] = new boolean[n+1];
        sieveOfEratosthenes(n, isPrime);
      
        // Checking whether the number
        // remains prime when the leading
        // ("left") digit is successively removed
        for (int i = cnt; i > 0; i--)
        {
            // Checking number by successively
            // removing leading ("left") digit.
            /* n=113, cnt=3
            i=3 mod=1000 n%mod=113
            i=2 mod=100 n%mod=13
            i=3 mod=10 n%mod=3 */
            int mod =  power(10,i);
      
            if (!isPrime[n%mod])
                return false;
        }
         
        // if remains prime, return true
        return true;
    }
      
    // Driver program
    public static void main(String args[])
    {
        int n = 113;
      
        if (leftTruPrime(n))
            System.out.println
                   (n+" is left truncatable prime");
        else
            System.out.println
                   (n+" is not left truncatable prime");
    }
}
 
/*This code is contributed by Nikita Tiwari.*/


Python3




# Python3 Program to
# check whether a
# given number is left
# truncatable prime
# or not.
 
# Function to calculate
# x raised to the power y
def power(x, y) :
     
    if (y == 0) :
        return 1
    elif (y % 2 == 0) :
        return(power(x, y // 2) *
               power(x, y // 2))
    else :
        return(x * power(x, y // 2) *
                power(x, y // 2))
 
# Generate all prime
# numbers less than n.
def sieveOfEratosthenes(n, isPrime) :
     
    # Initialize all entries
    # of boolean array
    # as true. A value in
    # isPrime[i] will finally
    # be false if i is Not a
    # prime, else true
    # bool isPrime[n+1];
    isPrime[0] = isPrime[1] = False
    for i in range(2, n+1) :
        isPrime[i] = True
         
    p=2
    while(p * p <= n) :
         
        # If isPrime[p] is not
        # changed, then it is
        # a prime
        if (isPrime[p] == True) :
             
            # Update all multiples
            # of p
            i=p*2
            while(i <= n) :
                isPrime[i] = False
                i = i + p
                 
        p = p + 1
         
# Returns true if n is
# right-truncatable,
# else false
def leftTruPrime(n) :
    temp = n
    cnt = 0
 
    # Counting number of
    # digits in the input
    # number and checking
    # whether it contains
    # 0 as digit or not.
    while (temp != 0) :
         
        # counting number
        # of digits.
        cnt=cnt + 1
         
        # checking whether
        # digit is 0 or not
        temp1 = temp % 10;
        if (temp1 == 0) :
             
            # if digit is 0,
            # return false.
            return False
         
        temp = temp // 10
 
    # Generating primes
    # using Sieve
    isPrime = [None] * (n + 1)
    sieveOfEratosthenes(n, isPrime)
 
    # Checking whether the
    # number remains prime
    # when the leading
    # ("left") digit is
    # successively removed
    for i in range(cnt, 0, -1) :
     
        # Checking number by
        # successively removing
        # leading ("left") digit.
        # n=113, cnt=3
        # i=3 mod=1000 n%mod=113
        # i=2 mod=100 n%mod=13
        # i=3 mod=10 n%mod=3
        mod = power(10, i)
 
        # checking prime
        if (isPrime[n % mod] != True) :
             
            # if not prime,
            # return false
            return False
             
    # if remains prime
    # , return true
    return True
 
# Driver program
n = 113
 
if (leftTruPrime(n)) :
    print(n, "is left truncatable prime")
else :
    print(n, "is not left truncatable prime")
     
# This code is contributed by Nikita Tiwari.


C#




// Program to check whether
// a given number is left
// truncatable prime or not.
using System;
 
class GFG {
          
    // Function to calculate x
    // raised to the power y
    static int power(int x, int y)
    {
        if (y == 0)
            return 1;
        else if (y%2 == 0)
            return power(x, y/2)
                   *power(x, y/2);
        else
            return x*power(x, y/2)
                   *power(x, y/2);
    }
       
    // Generate all prime
    // numbers less than n.
    static void sieveOfEratosthenes
                (int n, bool []isPrime)
    {
        // Initialize all entries of boolean
        // array as true. A value in isPrime[i]
        // will finally be false if i is Not
        // a prime, else true bool isPrime[n+1];
        isPrime[0] = isPrime[1] = false;
        for (int i = 2; i <= n; i++)
            isPrime[i] = true;
       
        for (int p = 2; p * p <= n; p++)
        {
            // If isPrime[p] is not changed,
            // then it is a prime
            if (isPrime[p] == true)
            {
                // Update all multiples of p
                for (int i = p * 2; i <= n; i += p)
                    isPrime[i] = false;
            }
        }
    }
       
    // Returns true if n is
    // right-truncatable, else false
    static bool leftTruPrime(int n)
    {
        int temp = n, cnt = 0, temp1;
       
        // Counting number of digits in the
        // input number and checking whether
        // it contains 0 as digit or not.
        while (temp != 0)
        {
            // counting number of digits.
            cnt++;
       
            temp1 = temp%10;
              
            // checking whether digit is
            // 0 or not
            if (temp1 == 0)
                return false;
            temp = temp/10;
        }
       
        // Generating primes using Sieve
        bool []isPrime = new bool[n+1];
        sieveOfEratosthenes(n, isPrime);
       
        // Checking whether the number
        // remains prime when the leading
        // ("left") digit is successively removed
        for (int i = cnt; i > 0; i--)
        {
            // Checking number by successively
            // removing leading ("left") digit.
            /* n=113, cnt=3
            i=3 mod=1000 n%mod=113
            i=2 mod=100 n%mod=13
            i=3 mod=10 n%mod=3 */
            int mod =  power(10, i);
       
            if (!isPrime[n%mod])
                return false;
        }
          
        // if remains prime, return true
        return true;
    }
       
    // Driver program
    public static void Main()
    {
        int n = 113;
       
        if (leftTruPrime(n))
            Console.WriteLine
                   (n + " is left truncatable prime");
        else
            Console.WriteLine
                   (n + " is not left truncatable prime");
    }
}
  
//This code is contributed by Anant Agarwal.


PHP




<?php
// PHP Program to check whether a
// given number is left-truncatable
// prime or not.
 
/* Function to calculate x raised to
the power y */
function power($x, $y)
{
    if ($y == 0)
        return 1;
    else if ($y % 2 == 0)
        return power($x, $y/2) *
                     power($x, $y/2);
    else
        return $x*power($x, $y/2) *
                     power($x, $y/2);
}
 
// Generate all prime numbers
// less than n.
function sieveOfEratosthenes($n, $l,
                            $isPrime)
{
     
    // Initialize all entries of
    // boolean array as true. A
    // value in isPrime[i] will
    // finally be false if i is
    // Not a prime, else true
    // bool isPrime[n+1];
    $isPrime[0] = $isPrime[1] = -1;
    for ($i = 2; $i <= $n; $i++)
        $isPrime[$i] = true;
 
    for ( $p = 2; $p * $p <= $n; $p++)
    {
        // If isPrime[p] is not
        // changed, then it is
        // a prime
        if ($isPrime[$p] == true)
        {
            // Update all multiples
            // of p
            for ($i = $p * 2; $i <= $n;
                              $i += $p)
                $isPrime[$i] = false;
        }
    }
}
 
// Returns true if n is
// right-truncatable, else false
function leftTruPrime($n)
{
    $temp = $n; $cnt = 0; $temp1;
 
    // Counting number of digits in
    // the input number and checking
    // whether it contains 0 as digit
    // or not.
    while ($temp)
    {
         
        // counting number of digits.
        $cnt++;
 
        // checking whether digit is
        // 0 or not
        $temp1 = $temp % 10;
         
        if ($temp1 == 0)
         
            // if digit is 0, return
            // false.
            return -1;
        $temp = $temp / 10;
    }
 
    // Generating primes using Sieve
    $isPrime[$n + 1];
    sieveOfEratosthenes($n, $isPrime);
 
    // Checking whether the number
    // remains prime when the leading
    // ("left") digit is successively
    // removed
    for ($i = $cnt; $i > 0; $i--)
    {
        // Checking number by
        // successively removing
        // leading ("left") digit.
        /* n=113, cnt=3
        i=3 mod=1000 n%mod=113
        i=2 mod=100 n%mod=13
        i=3 mod=10 n%mod=3 */
        $mod= power(10, $i);
 
        // checking prime
        if (!$isPrime[$n % $mod])
         
            // if not prime, return
            // false
            return -1;
    }
     
    // if remains prime, return true
    return true;
}
 
// Driver program
 
    $n = 113;
 
    if (leftTruPrime($n))
        echo $n, " is left truncatable",
                        " prime", "\n";
    else
        echo $n, " is not left ",
              "truncatable prime", "\n";
 
// This code is contributed by ajit
?>


Javascript




<script>
 
// Javascript program to check whether
// a given number is left
// truncatable prime or not.
 
    function power(x, y)
    {
        if (y == 0)
            return 1;
        else if (y%2 == 0)
            return power(x, Math.floor(y/2))
                   *power(x, Math.floor(y/2));
        else
            return x*power(x, Math.floor(y/2))
                   *power(x, Math.floor(y/2));
    }
      
    // Generate all prime
    // numbers less than n.
    function sieveOfEratosthenes
                (n, isPrime)
    {
         
        // Initialize all entries of boolean
        // array as true. A value in isPrime[i]
        // will finally be false if i is Not
        // a prime, else true bool isPrime[n+1];
        isPrime[0] = isPrime[1] = false;
        for (let i = 2; i <= n; i++)
            isPrime[i] = true;
      
        for (let p = 2; p*p <= n; p++)
        {
            // If isPrime[p] is not changed,
            // then it is a prime
            if (isPrime[p] == true)
            {
                 
                // Update all multiples of p
                for (let i = p*2; i <= n; i += p)
                    isPrime[i] = false;
            }
        }
    }
      
    // Returns true if n is
    // right-truncatable, else false
    function leftTruPrime(n)
    {
        let temp = n, cnt = 0, temp1;
      
        // Counting number of digits in the
        // input number and checking whether
        // it contains 0 as digit or not.
        while (temp != 0)
        {
            // counting number of digits.
            cnt++;
      
            temp1 = temp%10;
             
            // checking whether digit is
            // 0 or not
            if (temp1 == 0)
                return false;
            temp = Math.floor(temp/10);
        }
      
        // Generating primes using Sieve
        let isPrime = Array.from({length: n+1}, (_, i) => 0);
        sieveOfEratosthenes(n, isPrime);
      
        // Checking whether the number
        // remains prime when the leading
        // ("left") digit is successively removed
        for (let i = cnt; i > 0; i--)
        {
            // Checking number by successively
            // removing leading ("left") digit.
            /* n=113, cnt=3
            i=3 mod=1000 n%mod=113
            i=2 mod=100 n%mod=13
            i=3 mod=10 n%mod=3 */
            let mod =  power(10,i);
      
            if (!isPrime[n%mod])
                return false;
        }
         
        // if remains prime, return true
        return true;
    }
 
// Driver Code
 
    let n = 113;
      
        if (leftTruPrime(n))
            document.write
                   (n+" is left truncatable prime");
        else
             document.write
                   (n+" is not left truncatable prime");
 
// This code is contributed by sanjoy_62.
</script>


Output

113 is left truncatable prime

Time Complexity: O(N*N) 
Auxiliary Space: O(N)

Related Article : 
Right-Truncatable Prime
References: https://en.wikipedia.org/wiki/Truncatable_prime



Previous Article
Next Article

Similar Reads

Find coordinates of a prime number in a Prime Spiral
Introduction The Ulam spiral is a graphical depiction of the set of prime numbers, devised by mathematician Stanislaw Ulam. It is constructed by writing the positive integers in a square spiral and specially marking the prime numbers.You can read more about it here.But we are going to compute on the alternate version of this spiral where the prime
11 min read
Find the player to last modify a string such that even number of consonants and no vowels are left in the string
Given a string S of length N containing lowercase alphabets. Two players A and B play a game optimally in turns, starting with player A. In each move, either of the following operations can be performed: Remove a consonant from the string.If any character is a vowel, then convert it into any other alphabet. A player loses the game if there is an ev
7 min read
Maximum path sum from top left to bottom right of a matrix passing through one of the given cells
Given a matrix mat[][] of dimensions N * M and a set of coordinates of cell coordinates[][] of size Q, the task is to find the maximum sum of a path from the top-left cell (1, 1) to the bottom-right cell (N, M), such that the path should contain at least one of the coordinates from the array coordinates[][2]. The only moves allowed from any cell (i
15 min read
Maximum points by traversing from top left of Matrix to bottom right by two persons
Given a matrix grid[][] of order N*M with numbers 0-9 in the cells. The task is to find the maximum amount of money collected when two persons move from (0, 0) to (N-1, M-1) by moving only right and down. If both persons are at the same cell, then only one of them can pick the money at that location. Examples: Input: 1 1 1 1 0 1 1 1 1Output: 8Expla
7 min read
Lexicographically smallest binary string formed by flipping bits at indices not divisible K1 or K2 such that count of 1s is always greater than 0s from left
Given a binary string S(1-based indexing) of size N, and two positive integers K1 and K2, the task is to find the lexicographically smallest string by flipping the characters at indices that are not divisible by either K1 or K2 such that the count of 1s till every possible index is always greater than the count of 0s. If it is not possible to form
8 min read
Count greater elements on the left side of every array element
Given an array arr[] of distinct integers of size N, the task is to print the count of greater elements on the left side of each array element. Examples : Input: arr[] = {12, 1, 2, 3, 0, }Output: 0 1 1 1 4Explanation:For index 0, no greater element exists on the left side.For index 1, {12} is greater element on the left side.For index 2, {12} is gr
7 min read
Print all leaf nodes of a Binary Tree from left to right
Given a binary tree, we need to write a program to print all leaf nodes of the given binary tree from left to right. That is, the nodes should be printed in the order they appear from left to right in the given tree. For Example, For the above binary tree, the output will be as shown below: 4 6 7 9 10The idea to do this is similar to DFS algorithm.
12 min read
Minimize cost to reach bottom right from top left corner of Matrix with given separate cost for each move
Given an integer N and three N x N matrices X[][], Y[][], and Z[][], the task is to calculate the minimum cost required to reach the bottom right from the top left of the matrix using the following moves: Move to a cell in the right direction from (i, j) which will cost X[i][j].Move to a cell in the downward direction from (i, j) which will cost Y[
15+ min read
Prime number in PL/SQL
Prerequisite – PL/SQL introductionA prime number is a whole number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 â€Ķ..In PL/SQL code groups of commands are arranged within a block. A block group-related declarations or statements. In declare part, we declare variables and between begin a
1 min read
Prime Subset Product Problem
Given an array arr[] of N integers. The value of a subset of array A is defined as the product of all prime numbers in that subset. If there are no primes in the subset then the value of that subset is 1. The task is to calculate the product of values of all possible non-empty subsets of the given array modulus 100000007.Examples: Input: arr[] = {3
7 min read
Article Tags :
Practice Tags :