Given a range [low..high], print the smallest twin numbers in given range (low and high inclusive). Two numbers are twins if they are primes and there difference is 2.
Input: low = 10, high = 100 Output: Smallest twins in given range: (11, 13) Both 11 and 13 are prime numbers and difference between them is two, therefore twins. And these are the smallest twins in [10..100] Input: low = 50, high = 100 Output: Smallest twins in given range: (59, 61)
A Simple Solution is to start to start from low and for every number x check if x and x + 2 are primes are not. Here x varies from low to high-2.
An Efficient Solution is to use Sieve of Eratosthenes
1) Create a boolean array "prime[0..high]" and initialize all entries in it as true. A value in prime[i] will finally be false if i is not a prime number, else true. 2) Run a loop from p = 2 to high. a) If prime[p] is true, then p is prime. [See this] b) Mark all multiples of p as not prime in prime. 3) Run a loop from low to high and print the first twins using prime built in step 2.
Below is the implementation of above idea.
Smallest twins in given range: (11, 13)
Thanks to Utkarsh Trivedi for suggesting this solution.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- Find the largest twins in given range
- Find kth smallest number in range [1, n] when all the odd numbers are deleted
- Length of Smallest subarray in range 1 to N with sum greater than a given value
- Find smallest number with given number of digits and sum of digits under given constraints
- Count all the numbers in a range with smallest factor as K
- Find an integer in the given range that satisfies the given conditions
- Find the XOR of the elements in the given range [L, R] with the value K for a given set of queries
- Queries to increment array elements in a given range by a given value for a given number of times
- Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
- Generate a pair of integers from a range [L, R] whose LCM also lies within the range
- Given a number, find the next smallest palindrome
- Find the smallest number whose digits multiply to a given number n
- Find smallest permutation of given number
- Find smallest number n such that n XOR n+1 equals to given k.
- Find the lexicographically smallest string which satisfies the given condition
- Find the smallest positive number which can not be represented by given digits
- Find smallest possible Number from a given large Number with same count of digits
- Find smallest number formed by inverting digits of given number N
- Smallest index in the given array that satisfies the given condition
- Find numbers with K odd divisors in a given range