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 ; 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
function ugly ( a , size , n ) { if ( n <= 0 ) return - 1 ; if ( n == 1 ) return 1 ; let pq = [ ] ; ; for ( let i = 0 ; i < size ; i ++ ) { pq . push ( a [ i ] ) ; } let count = 1 , no ; pq . sort ( function ( a , b ) { return a - b ; } ) ; while ( count < n ) { no = pq . shift ( ) ; if ( no != pq [ 0 ] ) { count ++ ; for ( let i = 0 ; i < size ; i ++ ) { pq . push ( no * a [ i ] ) ; } } pq . sort ( function ( a , b ) { return a - b ; } ) ; } return no ; } let a = [ 2 , 3 , 5 ] ; let size = a . length ; document . write ( ugly ( a , size , 1000 ) ) ;