Largest Left-Truncatable Prime in a given base
Given an integer N representing the base of a number, the task is to find the largest left-truncatable prime in the given base N.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: N = 3
Left-truncatable prime in base N(= 3) are given below:
(12)3 = (5)10
(212)3 = (23)10
Therefore, the largest left-truncatable prime in base N(= 3) is (23)10.
Input: N = 5
Approach: The idea is to generate all left-truncatable prime numbers in the given base N and print the largest left-truncatable prime number based on the following observations:
If a number containing (i) digits is a left-truncatable prime number, then the numbers formed from the last (i – 1) digits must be a left-truncatable prime number.
Therefore, to make a left-truncatable prime number of digits i, first find all the left-truncatable prime numbers of (i – 1) digits.
- Initialize an array, say candidates, to store the all possible left truncatable prime numbers in the given base N.
- Iterate over the range [0, infinity] using variable i and insert all the left truncatable prime numbers of digits i. If no left truncatable number consisting of i digits is found, then return from the loop.
- Finally, print the maximum element present in the array candidates.
Below is the implementation of the above approach:
Time Complexity: O(k * log3N), where k is the rounds performed in Miller-Rabin primality test
Auxiliary Space: O(X), where X is the total count of left-truncatable prime in base N