Given a range [low..high], print the largest 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: Largest twins in given range: (71, 73) Input: low = 1, high = 20 Output: Largest twins in given range: (17, 19)
A Simple Solution is to start from high and for every number x check if x and x – 2 are primes are not. Here x varies from high to low + 2.
An Efficient Solution is to use Sieve of Eratosthenes:
- 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.
- Run a loop from p = 2 to high.
- If prime[p] is true, then p is prime.
- Mark all multiples of p as not prime in prime.
- Run a loop from high to low and print the first twins using prime built in step 2.
Largest twins in given range: (71, 73)
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 smallest twins in given range
- 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
- Sum of largest divisible powers of p (a prime number) in a range
- 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
- Legendre's formula (Given p and n, find the largest x such that p^x divides n!)
- Find the Largest number with given number of digits and sum of digits
- Find Largest Special Prime which is less than or equal to a given number
- Find the largest good number in the divisors of given number N
- Find the original matrix when largest element in a row and a column are given
- Find the largest contiguous pair sum in given Array
- Find numbers with K odd divisors in a given range
- Find numbers with n-divisors in a given range
- Find a range of composite numbers of given length
- Find and Count total factors of co-prime A or B in a given range 1 to N
- Find the GCD that lies in given range
- Program to find count of numbers having odd number of divisors in given range
- Find a distinct pair (x, y) in given range such that x divides y
- Find Prime Adam integers in the given range [L, R]
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.