Given an integer N, the task is to count the number of distinct prime triplets (a, b, c) from the range [1, N] such that a < b < c ≤ N and a + b = c.
Note: Two prime tuples are distinct if at least one of the primes present in them are different.
Input: N = 6
Explanation: Among numbers in the range [1, 6], the only prime triplet is (2, 3, 5) (Since 2 + 3 = 5).
Input: N = 10
Explanation: The distinct prime triplets satisfying the condition are (2, 3, 5), (2, 5, 7).
Approach: The problem can be solved based on the observation stated below:
For every prime number p from 1 to N, it is a part of a triplet if and only if it can be represented as a sum of two prime numbers.
Since a prime number is an odd number, it must be equal to the sum of an even number and an odd number.
Hence the only even prime is 2. Therefore, for a prime number p to constitute a unique tuple (2, p-2, p), the number p – 2 must be a prime number.
Follow the steps below to solve the problem:
- Initialize a variable, say count = 0, to store the number of prime triplets.
- Iterate from 1 to N and for each number p, check if this number p and p – 2 are prime or not.
- If they are prime, then increment count by 1.
- Print the value of count.
Below is the implementation of the above approach:
Time Complexity: O(N3/2)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.