
4 is a prime adjacent because it is adjacent to the numbers 3 and 5, which are prime numbers.
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.
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
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.
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 idea is to check separately if the number N - 1 and the number N + 1 are prime or not.
The approach is to check iteratively for a number if it is prime or not.
Note :
Rather than checking till N-1 for a number N, we can check till N/2. As any divisor of a number will not be greater than half of that number. But, this is a very minute improvement, the time complexity still remains the same.
Let us see how we can find out if a number X is prime or not.
The logic remains the same, we will check if the adjacent numbers are prime or not. For that we will use the below algorithm:
The approach is to precompute all prime numbers using the Sieve of Eratosthenes.
Modifications:
Let us take an example, 21 can be represented as 7 * 3.
→ Now, 21 is one of the multiples of 7, So we tried to mark it during the iteration when we take 7 as our prime number. But, if we look carefully, 21 is also the multiple of 3. This means that 21 was already marked earlier by 3 as non-prime.
→ In short, following the above algorithm, when I = 2, we marked 2 * 2, 2 * 3, 2 * 4, and so on as composite.
→ Now, when I = 3, we will mark 3 * 2, 3 * 3, 3 * 4, and so on as composite. You will see that 3 * 2 is repeated.
→ Now, when I = 5, we will mark 5 * 2, 5 * 3, 5 * 4, and so on as composite. You will see that 5 * 2 are 5 * 3 are repeated again and in the case of 5 * 4, we are iterating it unnecessarily as it must have been taken care of by 2 during 10 as multiple.
Modified Algorithm :
→ For i less then root(N):
→ If check[i] is true, for all multiples of i which are less than N, assign check[ j ] = false, where j is (i * i), (i * i + i), (i * i + 2 * i) and so on.
Sorted Doubly Linked List to Balanced BST
Longest Substring with K-Repeating Characters
Expression Add Operators
Gray Code Transformation
Count of Subsequences with Given Sum