Thursday, December 7, 2017

UVa 897 - Anagrammatic Primes

Problem Statement : https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=838

Hints : 

1. There is no Anagrammatic Prime in the interval [991,10000000]. So for any number N >= 991, it would be efficient to print 0. Therefore, checking prime upto 1000 is enough for this problem.

2. If any from the rest of primes have any even digit, it can't be an Anagrammatic Prime.

3. Now, just iterate the prime[] array upto 999 and check their digits and all the permutations also. If any of the permutation is not prime, the ith number can't be an Anagrammatic Prime.

4. Permutation can be generated by backtracking, but you can implement next_permutation from C++ STL. 😊

5. After checking all the Anagrammatic Primes, just store them in an array (I used std::vector).

6. Now, make l, the next power of 10 greater than n and run a loop from n+1 to l. Compare them with the stored Anagrammatic Primes. If found, print that. Otherwise, print 0.

Solution : Here is my solution uploaded on GitHub. Before seeing the solution ensure that you have tried enough. 😃