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
import java . io . * ; import java . util . * ; class GFG { static int digiSum ( int a ) { int sum = 0 ; while ( a != 0 ) { sum += a % 10 ; a = a / 10 ; } return sum ; } static boolean isPrime ( int r ) { boolean s = true ; for ( int i = 2 ; i * i <= r ; i ++ ) { if ( r % i == 0 ) { s = false ; break ; } } return s ; } static boolean 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 ; } static void FirstKMorannumber ( int [ ] a , int n , int k ) { int X = k ; Arrays . sort ( a ) ; TreeSet < Integer > s = new TreeSet < Integer > ( ) ; for ( int i = n - 1 ; i >= 0 && k > 0 ; i -- ) { if ( isMorannumber ( a [ i ] ) ) { s . add ( a [ i ] ) ; k -- ; } } if ( k > 0 ) { System . out . println ( X + " ▁ Moran ▁ numbers ▁ are " + " ▁ not ▁ present ▁ in ▁ the ▁ array " ) ; return ; } for ( int value : s ) System . out . print ( value + " , ▁ " ) ; System . out . print ( "NEW_LINE"); } public static void main ( String [ ] args ) { int [ ] A = { 34 , 198 , 21 , 42 , 63 , 45 , 22 , 44 , 43 } ; int K = 4 ; int N = A . length ; FirstKMorannumber ( A , N , K ) ; } }