Find Nth smallest number having exactly 4 divisors | Function to find the nth number which has exactly 4 divisors ; The divs [ ] array to store number of divisors of every element ; The vis [ ] array to check if given number is considered or not ; The cnt stores number of elements having exactly 4 divisors ; Iterate while cnt less than n ; If i is a prime ; Iterate in the range [ 2 * i , 1000000 ] with increment of i ; If the number j is already considered ; Dividing currNum by i until currNum % i is equal to 0 ; Case a single prime in its factorization ; Case of two distinct primes which divides j exactly once each ; Given Input ; Function Call
function nthNumber ( n ) { let divs = new Array ( 1000000 ) ; for ( var i = 0 ; i < divs . length ; i ++ ) { divs [ i ] = 0 ; } let vis = new Array ( 1000000 ) ; for ( var i = 0 ; i < vis . length ; i ++ ) { vis [ i ] = 0 ; } let cnt = 0 ; for ( let i = 2 ; cnt < n ; i ++ ) { if ( divs [ i ] == 0 ) { for ( let j = 2 * i ; j < 1000000 ; j += i ) { if ( vis [ j ] ) { continue ; } vis [ j ] = true ; let currNum = j ; let count = 0 ; while ( currNum % i == 0 ) { divs [ j ] ++ ; currNum = Math . floor ( currNum / i ) ; count ++ ; } if ( currNum == 1 && count == 3 && divs [ j ] == 3 ) { cnt ++ ; } else if ( currNum != 1 && divs [ currNum ] == 0 && count == 1 && divs [ j ] == 1 ) { cnt ++ ; } if ( cnt == n ) { return j ; } } } } return - 1 ; } let N = 24 ; document . write ( nthNumber ( N ) ) ;