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)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find the smallest twins in given range
- Sum of largest divisible powers of p (a prime number) in a range
- Find the largest possible k-multiple set
- Find the largest multiple of 2, 3 and 5
- Find largest number smaller than N with same set of digits
- Find largest prime factor of a number
- Legendre's formula (Given p and n, find the largest x such that p^x divides n!)
- Find the area of largest circle inscribed in ellipse
- Find the original matrix when largest element in a row and a column are given
- Find the largest number that can be formed by changing at most K digits
- Find Largest Special Prime which is less than or equal to a given number
- Find XOR of numbers from the range [L, R]
- Find Range Value of the Expression
- Find the GCD that lies in given range
- Find the length of the Largest subset such that all elements are Pairwise Coprime
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.