Program to find the Nth Composite Number - GeeksforGeeks

02 Jul, 2021
Given a positive integer N, the task is to find the Nth Composite Number.
Examples:
Input: N = 1Output: 4
Input: N = 3 Output: 8
Approach: The given problem can be solved by using the concept of Sieve of Eratosthenes. Follow the steps below to solve the problem:
Mark all the Prime Numbers till 105 in a boolean array say isPrime[] using Sieve of Eratosthenes.
Initialize an array, say composites[] that stores all the composite numbers.
Traverse the array isPrime[] using the variable i, if the value of isPrime[i] is false, then insert the number i in the array composites[].
After completing the above steps, print the value composites[N – 1] as the Nth Composite Number.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; #define MAX_SIZE 1000005 // Function to find the Nth Composite// Numbers using Sieve of Eratosthenesint NthComposite(int N){    // Sieve of prime numbers    bool IsPrime[MAX_SIZE];     // Initialize the array to true    memset(IsPrime, true, sizeof(IsPrime));     // Iterate over the range [2, MAX_SIZE]    for (int p = 2;         p * p < MAX_SIZE; p++) {         // If IsPrime[p] is true        if (IsPrime[p] == true) {             // Iterate over the            // range [p * p, MAX_SIZE]            for (int i = p * p;                 i < MAX_SIZE; i += p)                IsPrime[i] = false;        }    }     // Stores the list of composite numbers    vector<int> Composites;     // Iterate over the range [4, MAX_SIZE]    for (int p = 4; p < MAX_SIZE; p++)         // If i is not prime        if (!IsPrime[p])            Composites.push_back(p);     // Return Nth Composite Number    return Composites[N - 1];} // Driver Codeint main(){    int N = 4;    cout << NthComposite(N);    return 0;}
// Java program for the above approachimport java.util.*;public class GFG{ // Function to find the Nth Composite// Numbers using Sieve of Eratosthenespublic static int NthComposite(int N){    int MAX_SIZE = 1000005;       // Sieve of prime numbers    boolean[] IsPrime = new boolean[MAX_SIZE];     // Initialize the array to true    Arrays.fill(IsPrime, true);     // Iterate over the range [2, MAX_SIZE]    for (int p = 2; p * p < MAX_SIZE; p++) {         // If IsPrime[p] is true        if (IsPrime[p] == true) {             // Iterate over the            // range [p * p, MAX_SIZE]            for (int i = p * p;                 i < MAX_SIZE; i += p)                IsPrime[i] = false;        }    }     // Stores the list of composite numbers    Vector<Integer> Composites = new Vector<Integer>();     // Iterate over the range [4, MAX_SIZE]    for (int p = 4; p < MAX_SIZE; p++)         // If i is not prime        if (!IsPrime[p])            Composites.add(p);     // Return Nth Composite Number    return Composites.get(N - 1);} // Driver Code   public static void main(String args[])   {     int N = 4;     System.out.println(NthComposite(N));    }} // This code is contributed by SoumikMondal.
# Python3 program for the above approach # Function to find the Nth Composite# Numbers using Sieve of Eratosthenesdef NthComposite(N):       # Sieve of prime numbers    IsPrime = [True]*1000005     # Iterate over the range [2, 1000005]    for p in range(2, 1000005):        if p * p > 1000005:            break         # If IsPrime[p] is true        if (IsPrime[p] == True):                       # Iterate over the            # range [p * p, 1000005]            for i in range(p*p,1000005,p):                IsPrime[i] = False     # Stores the list of composite numbers    Composites = []     # Iterate over the range [4, 1000005]    for p in range(4,1000005):         # If i is not prime        if (not IsPrime[p]):            Composites.append(p)     # Return Nth Composite Number    return Composites[N - 1] # Driver Codeif __name__ == '__main__':    N = 4    print (NthComposite(N)) # This code is contributed by mohit kumar 29.
using System;using System.Collections.Generic; public class GFG{   // Function to find the Nth Composite  // Numbers using Sieve of Eratosthenes  public static int NthComposite(int N)  {    int MAX_SIZE = 1000005;     // Sieve of prime numbers    bool[] IsPrime = new bool[MAX_SIZE];     // Initialize the array to true    Array.Fill(IsPrime, true);     // Iterate over the range [2, MAX_SIZE]    for (int p = 2; p * p < MAX_SIZE; p++) {       // If IsPrime[p] is true      if (IsPrime[p] == true) {         // Iterate over the        // range [p * p, MAX_SIZE]        for (int i = p * p;             i < MAX_SIZE; i += p)          IsPrime[i] = false;      }    }     // Stores the list of composite numbers    List<int> Composites = new List<int>();     // Iterate over the range [4, MAX_SIZE]    for (int p = 4; p < MAX_SIZE; p++)       // If i is not prime      if (!IsPrime[p])        Composites.Add(p);     // Return Nth Composite Number    return Composites[N - 1];  }   // Driver Code  static public void Main ()  {     int N = 4;    Console.WriteLine(NthComposite(N));   }} // This code is contributed by patel2127
<script> // JavaScript program for the above approach let MAX_SIZE =  1000005; // Function to find the Nth Composite// Numbers using Sieve of Eratosthenesfunction NthComposite( N){    // Sieve of prime numbers    let IsPrime = [];     // Initialize the array to true    for(let i = 0;i<MAX_SIZE;i++)        IsPrime.push(true);     // Iterate over the range [2, MAX_SIZE]    for (let p = 2;         p * p < MAX_SIZE; p++) {         // If IsPrime[p] is true        if (IsPrime[p] == true) {             // Iterate over the            // range [p * p, MAX_SIZE]            for (let i = p * p;                 i < MAX_SIZE; i += p)                IsPrime[i] = false;        }    }     // Stores the list of composite numbers    let Composites = [];     // Iterate over the range [4, MAX_SIZE]    for (let p = 4; p < MAX_SIZE; p++)         // If i is not prime        if (!IsPrime[p])            Composites.push(p);     // Return Nth Composite Number    return Composites[N - 1];} // Driver Codelet N = 4;document.write(NthComposite(N)); </script>
9
 
Time Complexity: O(N + M * log(log(M)), where [2, M] is the range where Sieve of Eratosthenes is performed.Auxiliary Space: O(N)
mohit kumar 29
SoumikMondal
rohitsingh07052
saurabh1990aror
patel2127
Prime Number
sieve
Mathematical
Searching
Searching
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number