Given a number N, the task is to find the largest number less than or equal to the given number N such that on rearranging its digits it can become prime.
Input : N = 99 Output : 98 Explanation : We can rearrange the digits of 98 to 89 and 89 is a prime number. Input : N = 84896 Output : 84896 Explanation : We can rearrange the digits of 84896 to 46889 which is a prime number.
Below is the algorithm to find such a largest number num <= N such that digits of num can be rearranged to get a prime number:
Preprocessing Step: Generate a list of all the prime numbers less than or equal to given number N. This can be done efficiently using the sieve of Eratosthenes.
Main Steps: The main idea is to check all numbers from N to 1, if any of the number can be reshuffled to form a prime. The first such number found will be the answer.
To do this, run a loop from N to 1 and for every number:
- Extract the digits of the given number and store it in a vector.
- Sort this vector to get the smallest number which can be formed using these digits.
- For each permutation of this vector, we would form a number and check whether the formed number is prime or not. Here we make use of the Preprocessing step.
- If it is prime then we stop the loop and this is our answer.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Largest number not greater than N all the digits of which are odd
- Largest number with prime digits
- Smallest number by rearranging digits of a given number
- Find the Largest number with given number of digits and sum of digits
- Kth prime number greater than N
- Largest even digit number not greater than N
- Find next greater number with same set of digits
- Next greater Number than N with the same quantity of digits A and B
- Nearest greater number by interchanging the digits
- Largest number with maximum trailing nines which is less than N and greater than N-D
- Smallest Special Prime which is greater than or equal to a given number
- Smallest number greater than or equal to X whose sum of digits is divisible by Y
- 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
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.
Improved By : SURENDRA_GANGWAR