Given a positive integer N, the task is to find the Nth Composite Number.
Examples:
Input: N = 1
Output: 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++
#include <bits/stdc++.h>
using namespace std;
#define MAX_SIZE 1000005
int NthComposite( int N)
{
bool IsPrime[MAX_SIZE];
memset (IsPrime, true , sizeof (IsPrime));
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< int > Composites;
for ( int p = 4; p < MAX_SIZE; p++)
if (!IsPrime[p])
Composites.push_back(p);
return Composites[N - 1];
}
int main()
{
int N = 4;
cout << NthComposite(N);
return 0;
}
|
Java
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));
}
}
|
Python3
def NthComposite(N):
IsPrime = [ True ] * 1000005
for p in range ( 2 , 1000005 ):
if p * p > 1000005 :
break
if (IsPrime[p] = = True ):
for i in range (p * p, 1000005 ,p):
IsPrime[i] = False
Composites = []
for p in range ( 4 , 1000005 ):
if ( not IsPrime[p]):
Composites.append(p)
return Composites[N - 1 ]
if __name__ = = '__main__' :
N = 4
print (NthComposite(N))
|
C#
using System;
using System.Collections.Generic;
public class GFG{
public static int NthComposite( int N)
{
int MAX_SIZE = 1000005;
bool [] IsPrime = new bool [MAX_SIZE];
Array.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 ;
}
}
List< int > Composites = new List< int >();
for ( int p = 4; p < MAX_SIZE; p++)
if (!IsPrime[p])
Composites.Add(p);
return Composites[N - 1];
}
static public void Main ()
{
int N = 4;
Console.WriteLine(NthComposite(N));
}
}
|
Javascript
<script>
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));
</script>
|
Time Complexity: O(N + M * log(log(M)), where [2, M] is the range where Sieve of Eratosthenes is performed.
Auxiliary Space: O(N)
Program to find the Nth Composite Number in python using Brute Force approach
Example 2: By using Brute Force approach
Approach:
- Define a function is_composite(n) that takes a number n as input and returns True if n is composite (i.e., has a factor other than 1 and itself), and False otherwise. This function checks for factors by iterating from 2 to the square root of n, and returning True if any of these numbers divides n evenly.
- Define a function nth_composite_brute_force(n) that takes an integer n as input and returns the n-th composite number. The function initializes a counter count to 0, and a number num to 4 (since 4 is the smallest composite number).
- The function then enters a loop that continues until count is equal to n. Within the loop, the function checks if num is composite by calling the is_composite function. If num is composite, the function increments count by 1.
- Regardless of whether num is composite or not, the function increments num by 1 and continues to the next iteration of the loop.
- When the loop exits (i.e., when count is equal to n), the function returns the value of num minus 1 (since the loop incremented num one too many times).
- Overall, this approach checks every number starting from 4 until it finds the n-th composite number. Since it checks each number up to its square root, the time complexity of the is_composite function is O(sqrt(n)). Since we call this function for every number from 4 to the n-th composite number, the total time complexity of this approach is O(n^2 * sqrt(n)). The space complexity is O(1), since we only store a counter and a single number.
Python3
import time
def is_composite(n):
for i in range ( 2 , int (n * * 0.5 ) + 1 ):
if n % i = = 0 :
return True
return False
def nth_composite_brute_force(n):
count = 0
num = 4
while count < n:
if is_composite(num):
count + = 1
num + = 1
return num - 1
print ( "N = 1, Output = " , nth_composite_brute_force( 1 ))
print ( "N = 3, Output = " , nth_composite_brute_force( 3 ))
|
Output
N = 1, Output = 4
N = 3, Output = 8
Time Complexity: O(N^2 * logN)
Space Complexity: O(1)