For a given number N, the purpose is to find all the prime numbers from 1 to N.
Examples:
Input: N = 11
Output: 2, 3, 5, 7, 11
Input: N = 7
Output: 2, 3, 5, 7
Approach 1:
- Firstly, consider the given number N as input.
- Then apply a for loop in order to iterate the numbers from 1 to N.
- At last, check if each number is a prime number and if it’s a prime number then print it using brute-force method.
Java
class gfg {
static void prime_N( int N)
{
int x, y, flg;
System.out.println(
"All the Prime numbers within 1 and " + N
+ " are:" );
for (x = 1 ; x <= N; x++) {
if (x == 1 || x == 0 )
continue ;
flg = 1 ;
for (y = 2 ; y <= x / 2 ; ++y) {
if (x % y == 0 ) {
flg = 0 ;
break ;
}
}
if (flg == 1 )
System.out.print(x + " " );
}
}
public static void main(String[] args)
{
int N = 45 ;
prime_N(N);
}
}
|
Output
All the Prime numbers within 1 and 45 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43
Time Complexity: O(N2)
Auxiliary Space: O(1)
Approach 2:
- Firstly, consider the given number N as input.
- Then apply a for loop in order to iterate the numbers from 1 to N.
- At last, check if each number is a prime number and if it’s a prime number then print it using the square root method.
Java
class gfg {
static void prime_N( int N)
{
int x, y, flg;
System.out.println(
"All the Prime numbers within 1 and " + N
+ " are:" );
for (x = 2 ; x <= N; x++) {
flg = 1 ;
for (y = 2 ; y * y <= x; y++) {
if (x % y == 0 ) {
flg = 0 ;
break ;
}
}
if (flg == 1 )
System.out.print(x + " " );
}
}
public static void main(String[] args)
{
int N = 45 ;
prime_N(N);
}
}
|
Output
All the Prime numbers within 1 and 45 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43
Time Complexity: O(N3/2)
Approach 3:
Java
class SieveOfEratosthenes {
void sieveOfEratosthenes( int n)
{
boolean prime[] = new boolean [n + 1 ];
for ( int i = 0 ; i <= n; i++)
prime[i] = true ;
for ( int p = 2 ; p * p <= n; p++) {
if (prime[p] == true ) {
for ( int i = p * p; i <= n; i += p)
prime[i] = false ;
}
}
for ( int i = 2 ; i <= n; i++) {
if (prime[i] == true )
System.out.print(i + " " );
}
}
public static void main(String args[])
{
int N = 45 ;
System.out.println(
"All the Prime numbers within 1 and " + N
+ " are:" );
SieveOfEratosthenes g = new SieveOfEratosthenes();
g.sieveOfEratosthenes(N);
}
}
|
Output
All the Prime numbers within 1 and 45 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43
Time complexity : O(n*log(log(n)))
Auxiliary space: O(n) as using extra space for array prime
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
12 Sep, 2022
Like Article
Save Article