Super Ugly Number ( Number whose prime factors are in given set ) | function will return the nth super ugly number ; n cannot be negative hence return - 1 if n is 0 or - ve ; Declare a min heap priority queue ; Push all the array elements to priority queue ; once count = n we return no ; sorted ( pq ) Get the minimum value from priority_queue ; If top of pq is no then don 't increment count.  This to avoid duplicate counting of same no. ; Push all the multiples of no . to priority_queue ; cnt += 1 ; Return nth super ugly number ; Driver program to test above functions
def ugly ( a , size , n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT pq = [ ] NEW_LINE for i in range ( size ) : NEW_LINE INDENT pq . append ( a [ i ] ) NEW_LINE DEDENT count = 1 NEW_LINE no = 0 NEW_LINE pq = sorted ( pq ) NEW_LINE while ( count < n ) : NEW_LINE INDENT no = pq [ 0 ] NEW_LINE del pq [ 0 ] NEW_LINE if ( no != pq [ 0 ] ) : NEW_LINE INDENT count += 1 NEW_LINE for i in range ( size ) : NEW_LINE INDENT pq . append ( no * a [ i ] ) NEW_LINE DEDENT DEDENT pq = sorted ( pq ) NEW_LINE DEDENT return no NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 2 , 3 , 5 ] NEW_LINE size = len ( a ) NEW_LINE print ( ugly ( a , size , 1000 ) ) NEW_LINE DEDENT