Prime Sum With Adjacent Primes

You are given two integers n and k.

A prime number x is called special if it can be written in the following form: x = p[i] + p[i + 1] + 1

where p[i] and p[i + 1] are adjacent prime numbers, meaning there is no prime number between them.

Consider only special prime numbers that are in the range from 2 to n inclusive.

Return true if there are at least k such special prime numbers. Otherwise, return false.

Two prime numbers are called adjacent if they appear next to each other in the increasing list of prime numbers.

Example 1:

Input: n = 27, k = 2

Output: true

Explanation:

Prime numbers up to 27 are: 2, 3, 5, 7, 11, 13, 17, 19, 23.

Now check sums of adjacent primes plus 1:

  • 2 + 3 + 1 = 6 → not prime
  • 3 + 5 + 1 = 9 → not prime
  • 5 + 7 + 1 = 13 → prime
  • 7 + 11 + 1 = 19 → prime
  • 11 + 13 + 1 = 25 → not prime
  • 13 + 17 + 1 = 31 → greater than 27
  • remaining values will also be outside the range

The special primes within 2 to 27 are 13 and 19.

Since there are 2 such primes and k = 2, the answer is true.

Example 2:

Input: n = 20, k = 3

Output: false

Explanation:

Prime numbers up to 20 are: 2, 3, 5, 7, 11, 13, 17, 19.

Check adjacent prime sums plus 1:

  • 2 + 3 + 1 = 6 → not prime
  • 3 + 5 + 1 = 9 → not prime
  • 5 + 7 + 1 = 13 → prime
  • 7 + 11 + 1 = 19 → prime
  • 11 + 13 + 1 = 25 → not prime
  • further values exceed 20

There are only 2 special primes in range: 13 and 19.

Since 2 < 3, the answer is false.

Now Your Turn!

Pick the correct output for the given input

Input: n = 12, k = 1

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 2 <= n <= 1000
  • 0 <= k <= 1000

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
bool primeSum(int n, int k) {
// Your code goes here
}
};
Test Case

Input:

K
N