Find the largest twins in given range

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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.
?>

chevron_right


Output:

Largest twins in given range: (71, 73)


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.