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.
# Python3 program to find the smallest
# twin in given range
def printTwins(low, high):
# Create a boolean array “prime[0..high]”
# and initialize all entries it as true.
# A value in prime[i] will finally be
# false if i is Not a prime, else true.
prime = [True] * (high + 1);
twin = False;
prime = prime = False;
# Look for the smallest twin
for p in range(2, int(math.floor(
math.sqrt(high)) + 2)):
# If p is not marked, then it
# is a prime
# Update all multiples of p
for i in range(p * 2, high + 1, p):
prime[i] = False;
# Now print the smallest twin in range
for i in range(low, high + 1):
if (prime[i] and prime[i + 2]):
print(“Smallest twins in given range: (“,
i, “,”, (i + 2), “)”);
twin = True;
if (twin == False):
print(“No such pair exists”);
# Driver Code
# This code is contributed
# by chandan_jnu
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.
- Find the largest twins in given range
- Find kth smallest number in range [1, n] when all the odd numbers are deleted
- Count all the numbers in a range with smallest factor as K
- Find smallest number K such that K % p = 0 and q % K = 0
- Find smallest values of x and y such that ax - by = 0
- Find smallest number n such that n XOR n+1 equals to given k.
- Find smallest permutation of given number
- Given a number, find the next smallest palindrome
- Find the smallest number X such that X! contains at least Y trailing zeros.
- Program to find the smallest element among three elements
- Find the k-th smallest divisor of a natural number N
- Find the lexicographically smallest string which satisfies the given condition
- Find the GCD that lies in given range
- Find numbers with K odd divisors in a given range
- Find the occurrences of digit d in the range [0..n]