Open In App

Java Program to Display All Prime Numbers from 1 to N

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
5 Likes
Like
Report

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.

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.

 
 


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:


 


 

 
 


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


 


Java Program to Print Prime Numbers from 1 to 100
Article Tags :
Practice Tags :

Similar Reads