Program to print prime numbers from 1 to N.
Last Updated :
28 Feb, 2024
Given a number N, the task is to print the prime numbers from 1 to N.
Examples:
Input: N = 10
Output: 2, 3, 5, 7
Input: N = 5
Output: 2, 3, 5
Algorithm to print prime numbers:
- First, take the number N as input.
- Then use a for loop to iterate the numbers from 1 to N
- Then check for each number to be a prime number. If it is a prime number, print it.
Approach 1: Print prime numbers using loop.
Now, according to formal definition, a number ‘n’ is prime if it is not divisible by any number other than 1 and n. In other words a number is prime if it is not divisible by any number from 2 to n-1. so, we have to run a loop from 2 to n-1 and If a number is divisible by any number from 2 to n-1 it is not a prime number.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPrime( int n)
{
if (n == 1 || n == 0)
return false ;
for ( int i = 2; i < n; i++) {
if (n % i == 0)
return false ;
}
return true ;
}
int main()
{
int N = 100;
for ( int i = 1; i <= N; i++) {
if (isPrime(i))
cout << i << " " ;
}
return 0;
}
|
C
#include <stdbool.h>
#include <stdio.h>
bool isPrime( int n)
{
if (n == 1 || n == 0)
return false ;
for ( int i = 2; i < n; i++) {
if (n % i == 0)
return false ;
}
return true ;
}
int main()
{
int N = 100;
for ( int i = 1; i <= N; i++) {
if (isPrime(i))
printf ( "%d " , i);
}
return 0;
}
|
Java
class GFG
{
static boolean isPrime( int n){
if (n== 1 ||n== 0 ) return false ;
for ( int i= 2 ; i<n; i++){
if (n%i== 0 ) return false ;
}
return true ;
}
public static void main (String[] args)
{
int N = 100 ;
for ( int i= 1 ; i<=N; i++){
if (isPrime(i)) {
System.out.print(i + " " );
}
}
}
}
|
Python3
def isPrime(n):
if (n = = 1 or n = = 0 ): return False
for i in range ( 2 ,n):
if (n % i = = 0 ):
return False
return True
N = 100 ;
for i in range ( 1 ,N + 1 ):
if (isPrime(i)):
print (i,end = " " )
|
C#
using System;
class GFG
{
static bool isPrime( int n){
if (n==1||n==0) return false ;
for ( int i=2; i<n; i++) {
if (n%i==0) return false ;
}
return true ;
}
public static void Main (String[] args)
{
int N = 100;
for ( int i=1; i<=N; i++) {
if (isPrime(i)) {
Console.Write(i + " " );
}
}
}
}
|
Javascript
function isPrime(n) {
if (n == 1 || n == 0) return false ;
for ( var i = 2; i < n; i++) {
if (n % i == 0) return false ;
}
return true ;
}
var N = 100;
var result = [];
for ( var i = 1; i <= N; i++) {
if (isPrime(i)) {
result.push(i);
}
}
console.log(result.join( ' ' ));
|
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Time Complexity: O(N^2),
Auxiliary Space: O(1)
Approach 2: Optimize the first approach
For checking if a number is prime or not do we really need to iterate through all the number from 2 to n-1? We already know that a number ‘n’ cannot be divided by any number greater than ‘n/2’. So, according to this logic we only need to iterate through 2 to n/2 since number greater than n/2 cannot divide n.
C++
#include <bits/stdc++.h>
using namespace std;
bool isPrime( int n){
if (n==1||n==0) return false ;
for ( int i=2; i<=n/2; i++) {
if (n%i==0) return false ;
}
return true ;
}
int main()
{
int N = 100;
for ( int i=1; i<=N; i++){
if (isPrime(i)) {
cout << i << " " ;
}
}
return 0;
}
|
Java
class GFG
{
static boolean isPrime( int n){
if (n== 1 ||n== 0 ) return false ;
for ( int i= 2 ; i<=n/ 2 ; i++){
if (n%i== 0 ) return false ;
}
return true ;
}
public static void main (String[] args)
{
int N = 100 ;
for ( int i= 1 ; i<=N; i++){
if (isPrime(i)) {
System.out.print(i + " " );
}
}
}
}
|
Python3
def isPrime(n):
if (n = = 1 or n = = 0 ):
return False
for i in range ( 2 ,(n / / 2 ) + 1 ):
if (n % i = = 0 ):
return False
return True
N = 100 ;
for i in range ( 1 ,N + 1 ):
if (isPrime(i)):
print (i,end = " " )
|
C#
using System;
class GFG
{
static bool isPrime( int n){
if (n==1||n==0) return false ;
for ( int i=2; i<=n/2; i++){
if (n%i==0) return false ;
}
return true ;
}
public static void Main (String[] args)
{
int N = 100;
for ( int i=1; i<=N; i++){
if (isPrime(i)) {
Console.Write(i + " " );
}
}
}
}
|
Javascript
<script>
function isPrime(n)
{
if (n == 1 || n == 0) return false ;
for (let i = 2; i <= n / 2; i++)
{
if (n % i == 0) return false ;
}
return true ;
}
let N = 100;
for (let i = 1; i <= N; i++)
{
if (isPrime(i))
{
document.write(i + " " );
}
}
</script>
|
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Time Complexity: O(N2),
Auxiliary Space: O(1), since no extra space has been taken.
Approach 3:
If a number ‘n’ is not divided by any number less than or equals to the square root of n then, it will not be divided by any other number greater than the square root of n. So, we only need to check up to the square root of n.
C++
#include <bits/stdc++.h>
using namespace std;
bool isPrime( int n){
if (n==1||n==0) return false ;
for ( int i=2; i*i<=n; i++){
if (n%i==0) return false ;
}
return true ;
}
int main()
{
int N = 100;
for ( int i=1; i<=N; i++){
if (isPrime(i)) {
cout << i << " " ;
}
}
return 0;
}
|
Java
class GFG
{
static boolean isPrime( int n){
if (n== 1 ||n== 0 ) return false ;
for ( int i= 2 ; i*i<=n; i++){
if (n%i== 0 ) return false ;
}
return true ;
}
public static void main (String[] args)
{
int N = 100 ;
for ( int i= 1 ; i<=N; i++){
if (isPrime(i)) {
System.out.print(i + " " );
}
}
}
}
|
Python3
def isPrime(n):
if n = = 1 or n = = 0 :
return False
for i in range ( 2 , int (n * * ( 1 / 2 )) + 1 ):
if n % i = = 0 :
return False
return True
N = 100
for i in range ( 1 , N + 1 ):
if isPrime(i):
print (i, end = " " )
|
C#
using System;
class GFG
{
static bool isPrime( int n){
if (n==1||n==0) return false ;
for ( int i=2; i*i<=n; i++){
if (n%i==0) return false ;
}
return true ;
}
public static void Main (String[] args)
{
int N = 100;
for ( int i=1; i<=N; i++){
if (isPrime(i)) {
Console.Write(i + " " );
}
}
}
}
|
Javascript
<script>
const isPrime = (n) => {
if (n === 1||n === 0) return false ;
for (let i = 2; i <= Math.floor(Math.sqrt(n)); i++)
{
if (n % i == 0) return false ;
}
return true ;
}
let N = 100;
for (let i=1; i<=N; i++)
{
if (isPrime(i)) {
document.write(i+ " " );
}
}
</script>
|
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Time Complexity: O(N^(3/2)),
Auxiliary Space: O(1)
Approach 4: Sieve of Eratosthenes Algorithm
- Create a boolean array is_prime of size (N+1), initialized with true values for all elements.
- Loop through the array is_prime from 2 to the square root of N (inclusive), and for each prime number p found in the loop:
- If is_prime[p] is true, loop through the multiples of p from p*p up to N, and mark them as false in the is_prime array.
- Loop through the array is_prime from 2 to N (inclusive), and for each index i where is_prime[i] is true, print i as a prime number.
C++
#include <bits/stdc++.h>
using namespace std;
void sieve_of_eratosthenes( int n)
{
bool is_prime[n + 1];
memset (is_prime, true , sizeof (is_prime));
is_prime[0] = is_prime[1] = false ;
for ( int p = 2; p * p <= n; p++) {
if (is_prime[p]) {
for ( int i = p * p; i <= n; i += p) {
is_prime[i] = false ;
}
}
}
for ( int i = 2; i <= n; i++) {
if (is_prime[i]) {
cout << i << " " ;
}
}
}
int main()
{
sieve_of_eratosthenes(100);
return 0;
}
|
Java
import java.util.*;
public class GFG {
public static void sieve_of_eratosthenes( int n)
{
boolean [] is_prime = new boolean [n + 1 ];
Arrays.fill(is_prime, true );
is_prime[ 0 ] = is_prime[ 1 ] = false ;
for ( int p = 2 ; p * p <= n; p++) {
if (is_prime[p]) {
for ( int i = p * p; i <= n; i += p) {
is_prime[i] = false ;
}
}
}
for ( int i = 2 ; i <= n; i++) {
if (is_prime[i]) {
System.out.print(i + " " );
}
}
}
public static void main(String[] args)
{
sieve_of_eratosthenes( 100 );
}
}
|
Python3
def sieve_of_eratosthenes(n):
is_prime = [ True ] * (n + 1 )
is_prime[ 0 ] = is_prime[ 1 ] = False
for p in range ( 2 , int (n * * 0.5 ) + 1 ):
if is_prime[p]:
for i in range (p * p, n + 1 , p):
is_prime[i] = False
for i in range ( 2 , n + 1 ):
if is_prime[i]:
print (i, end = ' ' )
sieve_of_eratosthenes( 100 )
|
C#
using System;
public class GFG {
static public void sieve_of_eratosthenes( int n)
{
bool [] is_prime = new bool [n + 1];
Array.Fill(is_prime, true );
is_prime[0] = is_prime[1] = false ;
for ( int p = 2; p * p <= n; p++) {
if (is_prime[p]) {
for ( int i = p * p; i <= n; i += p) {
is_prime[i] = false ;
}
}
}
for ( int i = 2; i <= n; i++) {
if (is_prime[i]) {
Console.Write(i + " " );
}
}
}
static public void Main()
{
sieve_of_eratosthenes(100);
}
}
|
Javascript
function sieve_of_eratosthenes(n) {
let is_prime = new Array(n + 1).fill( true );
is_prime[0] = is_prime[1] = false ;
for (let p = 2; p * p <= n; p++) {
if (is_prime[p]) {
for (let i = p * p; i <= n; i += p) {
is_prime[i] = false ;
}
}
}
for (let i = 2; i <= n; i++) {
if (is_prime[i]) {
document.write(i+ " " );
}
}
}
sieve_of_eratosthenes(100);
|
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Complexity Analysis:
Time complexity:
- The outer loop runs from 2 to the square root of N, so it runs in O(sqrt(N)) time.
- The inner loop runs from p*p to N, and for each prime number p, it eliminates the multiples of p up to N. Therefore, the inner loop runs at most N/p times for each prime number p, so it has a time complexity of O(N/2 + N/3 + N/5 + …), which is approximately O(N log(log(N))). This is because the sum of the reciprocals of the prime numbers up to N is asymptotically bounded by log(log(N)).
- The final loop runs from 2 to N, so it has a time complexity of O(N).
- Therefore, the overall time complexity of the algorithm is O(N log(log(N))).
Space complexity:
- The algorithm uses an array of size N+1 to store the boolean values of whether each number is prime or not. Therefore, the space complexity is O(N).
In summary, the Sieve of Eratosthenes algorithm has a time complexity of O(N log(log(N))) and a space complexity of O(N) to print all the prime numbers from 1 to N.
To know more check Sieve of Eratosthenes.
Optimized Sieve of Eratosthenes Method: (Bitwise Sieve Method)
One optimization of the Sieve of Eratosthenes method is, we have skipped all even numbers altogether. We reduce the size of the prime array to half. We also reduce all iterations to half.
Steps:
- Create a boolean array prime of size (n/2), initialized with false values for all elements.
- As except 2, there are not any even prime numbers, so we skip 2 and then check for only odd numbers, so that we just have to check half elements.
- Inside the loop:
- In each iteration, if prime[i/2] is false, then loop through the multiples of i from i*i up to N with increment of 2*i, and mark them as true in the prime array.
- Finally, first print 2 and then loop through the array prime from 3 to N (inclusive), and for each index i/2 where prime[i/2] is false, print i as a prime number.
Below is the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void normalSieve( int n)
{
bool prime[n / 2];
memset (prime, false , sizeof (prime));
for ( int i = 3; i * i < n; i += 2) {
if (prime[i / 2] == false )
for ( int j = i * i; j < n; j += i * 2)
prime[j / 2] = true ;
}
printf ( "2 " );
for ( int i = 3; i < n; i += 2)
if (prime[i / 2] == false )
printf ( "%d " , i);
}
int main()
{
int n = 100;
normalSieve(n);
return 0;
}
|
Java
import java.util.Arrays;
class GFG {
public static void normalSieve( int n) {
boolean [] prime = new boolean [n / 2 ];
Arrays.fill(prime, false );
for ( int i = 3 ; i * i < n; i += 2 ) {
if (!prime[i / 2 ]) {
for ( int j = i * i; j < n; j += i * 2 ) {
prime[j / 2 ] = true ;
}
}
}
System.out.print( "2 " );
for ( int i = 3 ; i < n; i += 2 ) {
if (!prime[i / 2 ]) {
System.out.print(i + " " );
}
}
}
public static void main(String[] args) {
int n = 100 ;
normalSieve(n);
}
}
|
Python3
def normal_sieve(n):
prime = [ False ] * (n / / 2 )
for i in range ( 3 , int (n * * 0.5 ) + 1 , 2 ):
if not prime[i / / 2 ]:
for j in range (i * i, n, i * 2 ):
prime[j / / 2 ] = True
print ( 2 , end = " " )
for i in range ( 3 , n, 2 ):
if not prime[i / / 2 ]:
print (i, end = " " )
if __name__ = = "__main__" :
n = 100
normal_sieve(n)
|
C#
using System;
public class MainClass
{
public static void NormalSieve( int n)
{
bool [] prime = new bool [n / 2];
Array.Fill(prime, false );
for ( int i = 3; i * i < n; i += 2)
{
if (!prime[i / 2])
{
for ( int j = i * i; j < n; j += i * 2)
{
prime[j / 2] = true ;
}
}
}
Console.Write( "2 " );
for ( int i = 3; i < n; i += 2)
{
if (!prime[i / 2])
{
Console.Write(i + " " );
}
}
}
public static void Main( string [] args)
{
int n = 100;
NormalSieve(n);
}
}
|
Javascript
function normalSieve(n) {
let prime = new Array(n / 2).fill( false );
for (let i = 3; i * i < n; i += 2) {
if (!prime[Math.floor(i / 2)]) {
for (let j = i * i; j < n; j += i * 2) {
prime[Math.floor(j / 2)] = true ;
}
}
}
document.write( "2 " );
for (let i = 3; i < n; i += 2) {
if (!prime[Math.floor(i / 2)]) {
document.write(i + " " );
}
}
}
let n = 100;
normalSieve(n);
|
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Time Complexity: O(n*log(log n)), where n is the difference between the intervals.
Space Complexity: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...