Program to find the Nth Composite Number | Java 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
import java . util . * ; public class GFG { public static int NthComposite ( int N ) { int MAX_SIZE = 1000005 ; boolean [ ] IsPrime = new boolean [ MAX_SIZE ] ; Arrays . fill ( IsPrime , true ) ; for ( int p = 2 ; p * p < MAX_SIZE ; p ++ ) { if ( IsPrime [ p ] == true ) { for ( int i = p * p ; i < MAX_SIZE ; i += p ) IsPrime [ i ] = false ; } } Vector < Integer > Composites = new Vector < Integer > ( ) ; for ( int p = 4 ; p < MAX_SIZE ; p ++ ) if ( ! IsPrime [ p ] ) Composites . add ( p ) ; return Composites . get ( N - 1 ) ; } public static void main ( String args [ ] ) { int N = 4 ; System . out . println ( NthComposite ( N ) ) ; } }