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 math NEW_LINE def digiSum ( a ) : NEW_LINE INDENT sums = 0 NEW_LINE while ( a != 0 ) : NEW_LINE INDENT sums += a % 10 NEW_LINE a = a // 10 NEW_LINE DEDENT return sums NEW_LINE DEDENT def isPrime ( r ) : NEW_LINE INDENT s = True NEW_LINE for i in range ( 2 , int ( math . sqrt ( r ) ) + 1 ) : NEW_LINE INDENT if ( r % i == 0 ) : NEW_LINE INDENT s = False NEW_LINE break NEW_LINE DEDENT DEDENT return s NEW_LINE DEDENT def isMorannumber ( n ) : NEW_LINE INDENT dup = n NEW_LINE sums = digiSum ( dup ) NEW_LINE if ( n % sums == 0 ) : NEW_LINE INDENT c = n // sums NEW_LINE if isPrime ( c ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def FirstKMorannumber ( a , n , k ) : NEW_LINE INDENT X = k NEW_LINE a . sort ( ) NEW_LINE s = set ( ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( k <= 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( isMorannumber ( a [ i ] ) ) : NEW_LINE INDENT s . add ( a [ i ] ) NEW_LINE k -= 1 NEW_LINE DEDENT DEDENT if ( k > 0 ) : NEW_LINE INDENT print ( X , end = ' ▁ Moran ▁ numbers ▁ are ▁ not ▁ ' ' present ▁ in ▁ the ▁ array ' ) NEW_LINE return NEW_LINE DEDENT lists = sorted ( s ) NEW_LINE for i in lists : NEW_LINE INDENT print ( i , end = ' , ▁ ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 34 , 198 , 21 , 42 , 63 , 45 , 22 , 44 , 43 ] NEW_LINE K = 4 NEW_LINE N = len ( A ) NEW_LINE FirstKMorannumber ( A , N , K ) NEW_LINE DEDENT