Print first K distinct Moran numbers from a given array |  ; Function to calculate the sum of digits of a number ; Stores the sum of digits ; Add the digit to sum ; Remove digit ; Returns the sum of digits ; Function to check if a number is prime or not ; If r has any divisor ; Set r as non - prime ; Function to check if a number is moran number ; Calculate sum of digits ; Check if n is divisible by the sum of digits ; Calculate the quotient ; If the quotient is prime ; Function to print the first K Moran numbers from the array ; Sort the given array ; Initialise a set ; Traverse the array from the end ; If the current array element is a Moran number ; Insert into the set ; Driver Code
#include <algorithm> NEW_LINE #include <iostream> NEW_LINE #include <set> NEW_LINE using namespace std ; int digiSum ( int a ) { int sum = 0 ; while ( a ) { sum += a % 10 ; a = a / 10 ; } return sum ; } bool isPrime ( int r ) { bool s = true ; for ( int i = 2 ; i * i <= r ; i ++ ) { if ( r % i == 0 ) { s = false ; break ; } } return s ; } bool isMorannumber ( int n ) { int dup = n ; int sum = digiSum ( dup ) ; if ( n % sum == 0 ) { int c = n / sum ; if ( isPrime ( c ) ) { return true ; } } return false ; } void FirstKMorannumber ( int a [ ] , int n , int k ) { int X = k ; sort ( a , a + n ) ; set < int > s ; for ( int i = n - 1 ; i >= 0 && k > 0 ; i -- ) { if ( isMorannumber ( a [ i ] ) ) { s . insert ( a [ i ] ) ; k -- ; } } if ( k > 0 ) { cout << X << " ▁ Moran ▁ numbers ▁ are " << " ▁ not ▁ present ▁ in ▁ the ▁ array " << endl ; return ; } set < int > :: iterator it ; for ( it = s . begin ( ) ; it != s . end ( ) ; ++ it ) { cout << * it << " , ▁ " ; } cout << endl ; } int main ( ) { int A [ ] = { 34 , 198 , 21 , 42 , 63 , 45 , 22 , 44 , 43 } ; int K = 4 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; FirstKMorannumber ( A , N , K ) ; return 0 ; }