text: Check if the first and last digit of the smallest number forms a prime | C ++ implementation of above approach ; function to check prime ; Function to generate smallest possible number with given digits ; Declare a hash array of size 10 and initialize all the elements to zero ; store the number of occurrences of the digits in the given array into the hash table ; Traverse the hash in ascending order to print the required number ; Print the number of times a digits occurs ; extracting the first digit ; extracting the last digit ; printing the prime combinations ; Driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int isPrime ( int n ) { int i , c = 0 ; for ( i = 1 ; i < n / 2 ; i ++ ) { if ( n % i == 0 ) c ++ ; } if ( c == 1 ) return 1 ; else return 0 ; } void findMinNum ( int arr [ ] , int n ) { int first = 0 , last = 0 , num , rev , i ; int hash [ 10 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { hash [ arr [ i ] ] ++ ; } cout << " Minimum ▁ number : ▁ " ; for ( int i = 0 ; i <= 9 ; i ++ ) { for ( int j = 0 ; j < hash [ i ] ; j ++ ) cout << i ; } cout << endl ; for ( i = 0 ; i <= 9 ; i ++ ) { if ( hash [ i ] != 0 ) { first = i ; break ; } } for ( i = 9 ; i >= 0 ; i -- ) { if ( hash [ i ] != 0 ) { last = i ; break ; } } num = first * 10 + last ; rev = last * 10 + first ; cout << " Prime ▁ combinations : ▁ " ; if ( isPrime ( num ) && isPrime ( rev ) ) cout << num << " ▁ " << rev ; else if ( isPrime ( num ) ) cout << num ; else if ( isPrime ( rev ) ) cout << rev ; else cout << " No ▁ combinations ▁ exist " ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 7 , 8 } ; findMinNum ( arr , 5 ) ; return 0 ; }