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
function digiSum ( a ) { let sum = 0 ; while ( a ) { sum += a % 10 ; a = Math . floor ( a / 10 ) ; } return sum ; } function isPrime ( r ) { let s = true ; for ( let i = 2 ; i * i <= r ; i ++ ) { if ( r % i == 0 ) { s = false ; break ; } } return s ; } function isMorannumber ( n ) { let dup = n ; let sum = digiSum ( dup ) ; if ( n % sum == 0 ) { let c = n / sum ; if ( isPrime ( c ) ) { return true ; } } return false ; } function FirstKMorannumber ( a , n , k ) { let X = k ; a = a . sort ( ( x , y ) => x - y ) let s = new Set ( ) ; for ( let i = n - 1 ; i >= 0 && k > 0 ; i -- ) { if ( isMorannumber ( a [ i ] ) ) { s . add ( a [ i ] ) ; k -- ; } } if ( k > 0 ) { document . write ( X + " " + " " + " " ) ; return ; } s = [ ... s ] . sort ( ( a , b ) => a - b ) for ( let it of s ) { document . write ( it + " " ) ; } document . write ( " " ) ; } let A = [ 34 , 198 , 21 , 42 , 63 , 45 , 22 , 44 , 43 ] ; let K = 4 ; let N = A . length ; FirstKMorannumber ( A , N , K ) ;