Program to find the Nth Composite Number | JavaScript program for the above approach ; Function to find the Nth Composite Numbers using Sieve of Eratosthenes ; Sieve of prime numbers ; Initialize the array to true ; Iterate over the range [ 2 , MAX_SIZE ] ; If IsPrime [ p ] is true ; Iterate over the range [ p * p , MAX_SIZE ] ; Stores the list of composite numbers ; Iterate over the range [ 4 , MAX_SIZE ] ; If i is not prime ; Return Nth Composite Number ; Driver Code
let MAX_SIZE = 1000005 ; function NthComposite ( N ) { let IsPrime = [ ] ; for ( let i = 0 ; i < MAX_SIZE ; i ++ ) IsPrime . push ( true ) ; for ( let p = 2 ; p * p < MAX_SIZE ; p ++ ) { if ( IsPrime [ p ] == true ) { for ( let i = p * p ; i < MAX_SIZE ; i += p ) IsPrime [ i ] = false ; } } let Composites = [ ] ; for ( let p = 4 ; p < MAX_SIZE ; p ++ ) if ( ! IsPrime [ p ] ) Composites . push ( p ) ; return Composites [ N - 1 ] ; } let N = 4 ; document . write ( NthComposite ( N ) ) ;