Given a huge integer value n, find the largest integer value x such that x <= n and all the digits of x are prime.
Input : n = 45 Output : 37 37 is the largest number smaller than or equal to with all prime digits. Input : n = 1000 Output : 777 Input : n = 7721 Output : 7577 Input : n = 7221 Output : 5777
We know that the prime digits are 2, 3, 5 and 7. Also since we have to manipulate each digit of a very large number it will be easier if we do it as a string. The main idea is to find the first non-prime digit and then
find the first digit greater than 2 in its left. Now we can replace the found digit with the prime digit that is just less than it. If the digit is 2, we have to erase it and replace the next digit with 7. After this we can replace the remaining digits to its right by 7.
Following is the implementation of the above algorithm:
37 777 7577 5777 73777777777777777777777777777777777777777
The time complexity of the above program is O(N) where N is the length of the string.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Largest number not greater than N which can become prime after rearranging its digits
- Find the Largest number with given number of digits and sum of digits
- Largest number in [2, 3, .. n] which is co-prime with numbers in [2, 3, .. m]
- Largest number that divides x and is co-prime with y
- Largest number possible after removal of K digits
- Largest number not greater than N all the digits of which are odd
- Largest number with the given set of N digits that is divisible by 2, 3 and 5
- Recursive sum of digits of a number is prime or not
- Count of Prime digits in a Number
- Count of prime digits of a Number which divides the number
- Find largest prime factor of a number
- Sum of largest prime factor of each number less than equal to n
- Find largest number smaller than N with same set of digits
- Find all the prime numbers of given number of digits
- Finding n-th number made of prime digits (2, 3, 5 and 7) only
- Largest number less than N whose each digit is prime number
- Find Largest Special Prime which is less than or equal to a given number
- Queries for the smallest and the largest prime number of given digit
- Sum of largest divisible powers of p (a prime number) in a range
- Find the largest number that can be formed by changing at most K digits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.