Check if concatenation of first and last digits forms a prime number or not for each array element | C ++ program for the above approach ; Stores if i is prime ( 1 ) or non - prime ( 0 ) ; Function to build sieve array ; Inititalize all the values in sieve equals to 1 ; Sieve of Eratosthenes ; If current number is prime ; Set all multiples as non - prime ; Function to check if the numbers formed by combining first and last digits generates a prime number or not ; Check if any of the numbers formed is a prime number or not ; Traverse the array of queries ; Extract the last digit ; Extract the first digit ; If any of the two numbers is prime ; Otherwise ; Driver Code ; Computes and stores primes using Sieve ; Function call to perform queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sieve [ 105 ] ; void buildSieve ( ) { for ( int i = 2 ; i < 100 ; i ++ ) sieve [ i ] = 1 ; for ( int i = 2 ; i < 100 ; i ++ ) { if ( sieve [ i ] == 1 ) { for ( int j = i * i ; j < 100 ; j += i ) sieve [ j ] = 0 ; } } } bool isAnyPrime ( int first , int last ) { int num1 = first * 10 + last ; int num2 = last * 10 + first ; if ( sieve [ num1 ] == 1 sieve [ num2 ] == 1 ) return true ; else return false ; } void performQueries ( vector < int > q ) { for ( int i = 0 ; i < q . size ( ) ; i ++ ) { int A = q [ i ] ; int last = A % 10 ; int first ; while ( A >= 10 ) A = A / 10 ; first = A ; if ( isAnyPrime ( first , last ) ) cout << " True STRNEWLINE " ; else cout << " False STRNEWLINE " ; } } int main ( ) { vector < int > q = { 30 , 66 } ; buildSieve ( ) ; performQueries ( q ) ; return 0 ; }