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