Open In App

Find the largest twins in given range

Improve
Improve
Like Article
Like
Save
Share
Report

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.
Examples: 

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:

  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. 
    • If prime[p] is true, then p is prime.
    • Mark all multiples of p as not prime in prime[].
  3. Run a loop from high to low and print the first twins using prime[] built in step 2.

C++




// C++ program to find the largest twin in given range
#include <bits/stdc++.h>
using namespace std;
 
// Function to find twins
void printTwins(int low, int 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.
    bool prime[high + 1], twin = false;
    memset(prime, true, sizeof(prime));
 
    prime[0] = prime[1] = false;
 
    // Look for the smallest twin
    for (int p = 2; p <= floor(sqrt(high)) + 1; p++) {
 
        // If p is not marked, then it is a prime
        if (prime[p]) {
 
            // Update all multiples of p
            for (int i = p * 2; i <= high; i += p)
                prime[i] = false;
        }
    }
 
    // Now print the largest twin in range
    for (int i = high; i >= low; i--) {
        if (prime[i] && (i - 2 >= low && prime[i - 2] == true)) {
            cout << "Largest twins in given range: ("
                 << i - 2 << ", " << i << ")";
            twin = true;
            break;
        }
    }
 
    if (twin == false)
        cout << "No such pair exists" << endl;
}
 
// Driver program
int main()
{
    printTwins(10, 100);
 
    return 0;
}


Java




// Java program to find the
// largest twin in given range
import java.io.*;
 
class GFG
{
     
// Function to find twins
static void printTwins(int low, int 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.
    boolean prime[] = new boolean[high + 1];
    boolean twin = false;
    for(int i = 0; i < high + 1; i++)
    prime[i] = true;
 
    prime[0] = prime[1] = false;
 
    // Look for the smallest twin
    for (int p = 2;
             p <= Math.floor(Math.sqrt(high)) + 1; p++)
    {
 
        // If p is not marked,
        // then it is a prime
        if (prime[p])
        {
 
            // Update all multiples of p
            for (int i = p * 2; i <= high; i += p)
                prime[i] = false;
        }
    }
 
    // Now print the largest twin in range
    for (int i = high; i >= low; i--)
    {
        if (prime[i] && (i - 2 >= low &&
            prime[i - 2] == true))
        {
            System.out.println("Largest twins in given range: (" +
                                      (i - 2) + ", " + (i) + ")");
            twin = true;
            break;
        }
    }
 
    if (twin == false)
        System.out.println("No such pair exists");
}
 
// Driver Code
public static void main (String[] args)
{
    printTwins(10, 100);
}
}
 
// This code is contributed
// by inder_verma.


Python3




# Python 3 program to find the largest twin
# in given range
 
# Function to find twins
from math import sqrt,floor
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 for i in range(high + 1)]
    twin = False
 
    prime[0] = False
    prime[1] = False
 
    # Look for the smallest twin
    k = floor(sqrt(high)) + 2
    for p in range(2, k, 1):
         
        # If p is not marked, then it
        # is a prime
        if (prime[p]):
             
            # Update all multiples of p
            for i in range(p * 2, high + 1, p):
                prime[i] = False
         
    # Now print the largest twin in range
    i = high
    while(i >= low):
        if (prime[i] and (i - 2 >= low and
                          prime[i - 2] == True)):
            print("Largest twins in given range:(", (i - 2),   
                                             ",", (i), ")")
            twin = True
            break
             
        i -= 1
     
    if (twin == False):
        print("No such pair exists")
 
# Driver Code
if __name__ == '__main__':
    printTwins(10, 100)
 
# This code is contributed by
# Sanjit_Prasad


C#




// C# program to find the
// largest twin in given range
class GFG
{
     
// Function to find twins
static void printTwins(int low, int 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.
    bool[] prime = new bool[high + 1];
    bool twin = false;
    for(int i = 0; i < high + 1; i++)
    prime[i] = true;
 
    prime[0] = prime[1] = false;
 
    // Look for the smallest twin
    for (int p = 2;
             p <= System.Math.Floor(
                         System.Math.Sqrt(high)) + 1; p++)
    {
 
        // If p is not marked,
        // then it is a prime
        if (prime[p])
        {
 
            // Update all multiples of p
            for (int i = p * 2; i <= high; i += p)
                prime[i] = false;
        }
    }
 
    // Now print the largest twin in range
    for (int i = high; i >= low; i--)
    {
        if (prime[i] && (i - 2 >= low &&
            prime[i - 2] == true))
        {
            System.Console.WriteLine("Largest twins in given range: (" +
                                    (i - 2) + ", " + (i) + ")");
            twin = true;
            break;
        }
    }
 
    if (twin == false)
        System.Console.WriteLine("No such pair exists");
}
 
// Driver Code
public static void Main()
{
    printTwins(10, 100);
}
}
 
// This code is contributed
// by mits


Javascript




<script>
 
    // Javascript program to find the
    // largest twin in given range
     
    // Function to find twins
    function 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.
        let prime = new Array(high + 1);
        let twin = false;
        for(let i = 0; i < high + 1; i++)
            prime[i] = true;
 
        prime[0] = prime[1] = false;
 
        // Look for the smallest twin
        for (let p = 2; p <=
        Math.floor(Math.sqrt(high)) + 1; p++)
        {
 
            // If p is not marked,
            // then it is a prime
            if (prime[p])
            {
 
                // Update all multiples of p
                for (let i = p * 2; i <= high; i += p)
                    prime[i] = false;
            }
        }
 
        // Now print the largest twin in range
        for (let i = high; i >= low; i--)
        {
            if (prime[i] && (i - 2 >= low &&
            prime[i - 2] == true))
            {
                document.write(
                "Largest twins in given range: (" +
                (i - 2) + ", " + (i) + ")" + "</br>"
                );
                twin = true;
                break;
            }
        }
 
        if (twin == false)
            document.write("No such pair exists");
    }
     
    printTwins(10, 100);
                                  
</script>


PHP




<?php
//PHP  program to find the largest twin in given range
// Function to find twins
function  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[$high + 1]=array();
    $twin = false;
    $prime = array_fill(0, ($high + 1), true);
     
    $prime[0] = $prime[1] = false;
 
    // Look for the smallest twin
    for ($p = 2; $p <= floor(sqrt($high)) + 1; $p++) {
 
        // If p is not marked, then it is a prime
        if ($prime[$p]) {
 
            // Update all multiples of p
            for ($i = $p * 2; $i <= $high; $i += $p)
                $prime[$i] = false;
        }
    }
 
    // Now print the largest twin in range
    for ($i = $high; $i >= $low; $i--) {
        if ($prime[$i] && ($i - 2 >= $low && $prime[$i - 2] == true)) {
            echo "Largest twins in given range: (",
                $i - 2 , ", " , $i , ")";
            $twin = true;
            break;
        }
    }
 
    if ($twin == false)
         echo  "No such pair exists" ;
}
 
// Driver program
 
    printTwins(10, 100);
 
#This code is contributed by ajit.
?>


Output

Largest twins in given range: (71, 73)


Time Complexity: O(high*log(log(high)))
Auxiliary Space: O(high)

Another Approach:

  • Define a function is_prime that takes an integer as input and returns true if it is a prime number, false otherwise.
  • Define a function find_largest_twins that takes the start and end of the range as input, and finds the largest twin primes within that range.
    • In the find_largest_twins function, loop through the range from start to end, and check if each number and the number two greater than it are prime using the is_prime function.
    •  If a pair of twin primes is found, update the values of largest_prime and largest_twin_prime to the larger and smaller of the two primes, respectively.
    •  If no twin primes are found in the range, print a message saying so.
    •  If twin primes are found, print a message with the values of start, end, largest_twin_prime, and largest_prime.
  •  In the main function, set the values of start and end to the desired range, and call the find_largest_twins function with these values.

C++




#include <iostream>
using namespace std;
 
bool is_prime(int n)
{
    if (n < 2) {
        return false;
    }
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}
 
void find_largest_twins(int start, int end)
{
    int largest_prime = 0;
    int largest_twin_prime = 0;
    for (int i = start; i <= end; i++) {
        if (is_prime(i) && is_prime(i + 2)) {
            largest_prime = i + 2;
            largest_twin_prime = i;
        }
    }
    if (largest_twin_prime == 0) {
        cout << "No twin primes found in the given range\n";
    }
    else {
        cout << "The largest twin primes in the range ["
             << start << "," << end << "]"
             << " are " << largest_twin_prime << " and "
             << largest_prime;
    }
}
 
int main()
{
    int start = 100;
    int end = 1000;
    find_largest_twins(start, end);
    return 0;
}
 
// this code is contributed by shivanisingh.ss2110


C




#include <stdbool.h>
#include <stdio.h>
 
bool is_prime(int n)
{
    if (n < 2) {
        return false;
    }
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}
 
void find_largest_twins(int start, int end)
{
    int largest_prime = 0;
    int largest_twin_prime = 0;
    for (int i = start; i <= end; i++) {
        if (is_prime(i) && is_prime(i + 2)) {
            largest_prime = i + 2;
            largest_twin_prime = i;
        }
    }
    if (largest_twin_prime == 0) {
        printf("No twin primes found in the given range\n");
    }
    else {
        printf("The largest twin primes in the range [%d, "
               "%d] are %d and %d\n",
               start, end, largest_twin_prime,
               largest_prime);
    }
}
 
int main()
{
    int start = 100;
    int end = 1000;
    find_largest_twins(start, end);
    return 0;
}


Java




public class LargestTwinPrimes {
 
    // Function to check if a number is prime
    static boolean isPrime(int n) {
        if (n < 2) {
            return false// Numbers less than 2 are not prime
        }
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) {
                return false// If n is divisible by any number in the range [2, sqrt(n)], it's not prime
            }
        }
        return true// If no divisors are found, n is prime
    }
 
    // Function to find and print the largest twin prime numbers in the given range
    static void findLargestTwins(int start, int end) {
        int largestPrime = 0;
        int largestTwinPrime = 0;
         
        // Iterate through the range [start, end]
        for (int i = start; i <= end; i++) {
            if (isPrime(i) && isPrime(i + 2)) {
                largestPrime = i + 2// Store the larger prime of the twin primes
                largestTwinPrime = i;  // Store the smaller prime of the twin primes
            }
        }
         
        // Check if any twin primes were found in the given range
        if (largestTwinPrime == 0) {
            System.out.println("No twin primes found in the given range");
        } else {
            // Print the largest twin primes and the range
            System.out.println("The largest twin primes in the range [" + start + "," + end + "] are " +
                    largestTwinPrime + " and " + largestPrime);
        }
    }
 
    public static void main(String[] args) {
        int start = 100;
        int end = 1000;
        findLargestTwins(start, end);
    }
}


Python3




# Function to check if a number is prime
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True
 
# Function to find the largest twin primes in a given range
def find_largest_twins(start, end):
    largest_prime = 0
    largest_twin_prime = 0
    for i in range(start, end + 1):
        if is_prime(i) and is_prime(i + 2):
            largest_prime = i + 2
            largest_twin_prime = i
    if largest_twin_prime == 0:
        print("No twin primes found in the given range")
    else:
        print(
            f"The largest twin primes in the range [{start},{end}] are {largest_twin_prime} and {largest_prime}")
 
# Main function to call find_largest_twins function with start and end values
start = 100
end = 1000
find_largest_twins(start, end)


C#




// C# program to find the largest twin in the given range
using System;
 
class GFG
{
    // Function to check if a number is prime
    static bool IsPrime(int n)
    {
        if (n < 2)
        {
            return false;
        }
        for (int i = 2; i <= Math.Sqrt(n); i++)
        {
            if (n % i == 0)
            {
                return false;
            }
        }
        return true;
    }
 
    // Function to find the largest twin primes in a given range
    static void FindLargestTwins(int start, int end)
    {
        int largestPrime = 0;
        int largestTwinPrime = 0;
        for (int i = start; i <= end; i++)
        {
            if (IsPrime(i) && IsPrime(i + 2))
            {
                largestPrime = i + 2;
                largestTwinPrime = i;
            }
        }
        if (largestTwinPrime == 0)
        {
            Console.WriteLine("No twin primes found in the given range");
        }
        else
        {
            Console.WriteLine($"The largest twin primes in the range [{start},{end}] are {largestTwinPrime} and {largestPrime}");
        }
    }
 
    // Main function to call FindLargestTwins function with start and end values
    static void Main()
    {
        int start = 100;
        int end = 1000;
        FindLargestTwins(start, end);
    }
}
// The code is contributed by Nidhi goel.


Javascript




// Javascript code addition
 
function isPrime(n) {
  if (n < 2) {
    return false;
  }
  for (let i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      return false;
    }
  }
  return true;
}
 
function findLargestTwins(start, end) {
  let largestPrime = 0;
  let largestTwinPrime = 0;
  for (let i = start; i <= end; i++) {
    if (isPrime(i) && isPrime(i + 2)) {
      largestPrime = i + 2;
      largestTwinPrime = i;
    }
  }
  if (largestTwinPrime == 0) {
    console.log("No twin primes found in the given range");
  } else {
    console.log(
      `The largest twin primes in the range [${start},${end}] are ${largestTwinPrime} and ${largestPrime}`
    );
  }
}
 
const start = 100;
const end = 1000;
findLargestTwins(start, end);
 
// The code is contributed by Arushi Goel.


Output

The largest twin primes in the range [100, 1000] are 881 and 883


The time complexity of the is_prime function is O(sqrt(n)), and it is called for each number in the range from start to end. Therefore, the time complexity of the find_largest_twins function is O((end – start + 1) * sqrt(end)), which is roughly equivalent to O(n * sqrt(n)).

The Auxiliary space of the program is O(1) since it only uses a constant amount of memory regardless of the size of the input range.



Last Updated : 28 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads