A prime adjacent is a number that is adjacent to two prime numbers. Two numbers are considered adjacent to each other if the absolute difference between them is 1.
For Example:4 is a prime adjacent because it is adjacent to the numbers 3 and 5, which are prime numbers.
Your task is to find out if the number given to you is prime adjacent or not.
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then, the T test cases follow.
The first and only line of each test case or query contains an integer N.
Output format:
For each test case, print “Yes” if N is prime adjacent, otherwise print “No” (without inverted commas), in a separate line.
1 <= T <= 1000
2 <= N <= 10^6
Time limit: 1 sec
2
4
2
Yes
No
For test case 1:
4 is a prime adjacent because its adjacent numbers, 3 and 5 are prime numbers.
For test case 2:
In case of 2, the adjacent numbers are 1 and 3, out of which 1 is not prime but 3 is
prime.
By definition, a number is a prime adjacent only if both of its adjacent numbers are prime numbers. So, 2 is not a prime adjacent.
3
3
18
25
No
Yes
No
The very first approach can be to check whether the number N-1 and the number N+1 are prime or not. The idea is to use recursion for this task.
The first thing to observe is that all the odd numbers are non-prime adjacent as their adjacent numbers are always even (which are divisible by 2). So, if the given number is odd, simply return false. Thus, our target is to check only for even numbers.
Now the approach is to check recursively for a number if it is prime or not.
O(N) per test case, where N is the given number.
In the worst case, the checker function is called for max N times.
O(N) per test case.
In the worst case, extra space is used by the recursion stack which goes to a maximum depth of N.