Program to print prime numbers from 1 to N. - GeeksforGeeks

07 Mar, 2022
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:  
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:  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.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to display Prime numbers till N#include <bits/stdc++.h>using namespace std; //function to check if a given number is primebool isPrime(int n){      //since 0 and 1 is not prime return false.      if(n==1||n==0) return false;         //Run a loop from 2 to n-1      for(int i=2; i<n; i++){        // if the number is divisible by i, then n is not a prime number.        if(n%i==0) return false;      }      //otherwise, n is prime number.      return true;}  // Driver codeint main(){    int N = 100;     //check for every number from 1 to N      for(int i=1; i<=N; i++){          //check if current number is prime          if(isPrime(i)) {            cout << i << " ";          }    }     return 0;}
// Java program to display Prime numbers till Nclass GFG{      //function to check if a given number is prime     static boolean isPrime(int n){          //since 0 and 1 is not prime return false.          if(n==1||n==0)return false;             //Run a loop from 2 to n-1          for(int i=2; i<n; i++){            // if the number is divisible by i, then n is not a prime number.                if(n%i==0)return false;          }          //otherwise, n is prime number.          return true;    }          // Driver code    public static void main (String[] args)    {        int N = 100;        //check for every number from 1 to N        for(int i=1; i<=N; i++){            //check if current number is prime            if(isPrime(i)) {                System.out.print(i + " ");            }        }     }}
# Python3 program to display Prime numbers till N #function to check if a given number is primedef isPrime(n):  #since 0 and 1 is not prime return false.  if(n==1 or n==0):    return False     #Run a loop from 2 to n-1  for i in range(2,n):    #if the number is divisible by i, then n is not a prime number.    if(n%i==0):      return False     #otherwise, n is prime number.  return True   # Driver codeN = 100;#check for every number from 1 to Nfor i in range(1,N+1):  #check if current number is prime  if(isPrime(i)):    print(i,end=" ")
// C# program to display Prime numbers till Nusing System;     class GFG{        //function to check if a given number is prime     static bool isPrime(int n){        //since 0 and 1 is not prime return false.        if(n==1||n==0) return false;         //Run a loop from 2 to n-1        for(int i=2; i<n; i++) {            // if the number is divisible by i, then n is not a prime number.            if(n%i==0) return false;        }      //otherwise, n is prime number.      return true;    }     // Driver code    public static void Main (String[] args)    {        int N = 100;        //check for every number from 1 to N        for(int i=1; i<=N; i++) {          //check if current number is prime            if(isPrime(i)) {              Console.Write(i + " ");            }        }     }} // This code is contributed by Rajput-Ji
<script>  // JavaScript program to display Prime numbers till N // function to check if a given number is primefunction isPrime( n){      // since 0 and 1 is not prime return false.      if(n == 1 || n == 0) return false;         // Run a loop from 2 to n-1      for(var i = 2; i < n; i++)      {               // if the number is divisible by i, then n is not a prime number.        if(n % i == 0) return false;      }      // otherwise, n is prime number.      return true;}  // Driver codevar N = 100; // check for every number from 1 to N  for(var i = 1; i <= N; i++)  {      // check if current number is prime      if(isPrime(i)) {        console.log( i );      }} // This code is contributed by ukasp.</script>
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), Space Complexity: O(1)
Approach 2:  For checking if a number is prime or not do we really need to iterate through all the number form 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++
Java
Python3
C#
Javascript
// C++ program to display Prime numbers till N#include <bits/stdc++.h>using namespace std; //function to check if a given number is primebool isPrime(int n){    //since 0 and 1 is not prime return false.    if(n==1||n==0) return false;     //Run a loop from 2 to n/2.    for(int i=2; i<=n/2; i++) {          // if the number is divisible by i, then n is not a prime number.          if(n%i==0) return false;    }    //otherwise, n is prime number.    return true;}  // Driver codeint main(){    int N = 100;     //check for every number from 1 to N      for(int i=1; i<=N; i++){        //check if current number is prime        if(isPrime(i)) {          cout << i << " ";        }    }     return 0;}
// Java program to display// Prime numbers till Nclass GFG{     //function to check if a given number is prime     static boolean isPrime(int n){          //since 0 and 1 is not prime return false.          if(n==1||n==0) return false;         //Run a loop from 2 to n-1        for(int i=2; i<=n/2; i++){            // if the number is divisible by i, then n is not a prime number.            if(n%i==0)return false;        }        //otherwise, n is prime number.        return true;    }          // Driver code    public static void main (String[] args)    {        int N = 100;        //check for every number from 1 to N        for(int i=1; i<=N; i++){            //check if current number is prime            if(isPrime(i)) {              System.out.print(i + " ");            }        }     }}
# Python3 program to display Prime numbers till N #function to check if a given number is primedef isPrime(n):  #since 0 and 1 is not prime return false.  if(n==1 or n==0):    return False     #Run a loop from 2 to n/2  for i in range(2,(n//2)+1):    #if the number is divisible by i, then n is not a prime number.    if(n%i==0):      return False     #otherwise, n is prime number.  return True   # Driver codeN = 100;#check for every number from 1 to Nfor i in range(1,N+1):  #check if current number is prime  if(isPrime(i)):    print(i,end=" ")
// C# program to display// Prime numbers till Nusing System;     class GFG{    //function to check if a given number is prime static bool isPrime(int n){      //since 0 and 1 is not prime return false.     if(n==1||n==0)return false;         //Run a loop from 2 to n/2.      for(int i=2; i<=n/2; i++){        // if the number is divisible by i, then n is not a prime number.        if(n%i==0)return false;      }  //otherwise, n is prime number.  return true;} // Driver codepublic static void Main (String[] args){    int N = 100;    //check for every number from 1 to N      for(int i=1; i<=N; i++){      //check if current number is prime      if(isPrime(i)) {        Console.Write(i + " ");      }    }     }} // This code is contributed by Rajput-Ji
<script>// Javascript program to display Prime numbers till N // function to check if a given number is primefunction isPrime(n){     // since 0 and 1 is not prime return false.    if(n == 1 || n == 0) return false;     // Run a loop from 2 to n/2.    for(let i = 2; i <= n / 2; i++)    {          // if the number is divisible by i, then n is not a prime number.          if(n % i == 0) return false;    }         // otherwise, n is prime number.    return true;}  // Driver codelet N = 100; // check for every number from 1 to Nfor(let i = 1; i <= N; i++){    // check if current number is prime    if(isPrime(i))    {        document.write(i + " ");    }} // This code is contributed by shubham348.</script>
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), Space Complexity: O(1)
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++
Java
Python3
C#
Javascript
// C++ program to display Prime numbers till N#include <bits/stdc++.h>using namespace std; //function to check if a given number is primebool isPrime(int n){  //since 0 and 1 is not prime return false.  if(n==1||n==0)return false;     //Run a loop from 2 to square root of n.  for(int i=2; i*i<=n; i++){    // if the number is divisible by i, then n is not a prime number.    if(n%i==0)return false;  }  //otherwise, n is prime number.  return true;}  // Driver codeint main(){    int N = 100;     //check for every number from 1 to N      for(int i=1; i<=N; i++){      //check if current number is prime      if(isPrime(i)) {        cout << i << " ";      }    }     return 0;}
// Java program to display// Prime numbers till Nclass GFG{  //function to check if a given number is prime static boolean isPrime(int n){  //since 0 and 1 is not prime return false.  if(n==1||n==0)return false;     //Run a loop from 2 to square root of n  for(int i=2; i*i<=n; i++){    // if the number is divisible by i, then n is not a prime number.    if(n%i==0)return false;  }  //otherwise, n is prime number.  return true;}      // Driver codepublic static void main (String[] args){    int N = 100;        //check for every number from 1 to N      for(int i=1; i<=N; i++){      //check if current number is prime      if(isPrime(i)) {        System.out.print(i + " ");      }    }     }}
# Python3 program to display Prime numbers till N #function to check if a given number is primedef isPrime(n):  #since 0 and 1 is not prime return false.  if(n==1 or n==0):    return False     #Run a loop from 2 to square root of n.  for i in range(2,int(n**(1/2))+1):    #if the number is divisible by i, then n is not a prime number.    if(n%i==0):      return False     #otherwise, n is prime number.  return True   # Driver codeN = 100;#check for every number from 1 to Nfor i in range(1,N+1):  #check if current number is prime  if(isPrime(i)):    print(i,end=" ")
// C# program to display// Prime numbers till Nusing System;     class GFG{    //function to check if a given number is prime static bool isPrime(int n){      //since 0 and 1 is not prime return false.     if(n==1||n==0)return false;         //Run a loop from 2 to square root of n.      for(int i=2; i*i<=n; i++){        // if the number is divisible by i, then n is not a prime number.        if(n%i==0)return false;      }  //otherwise, n is prime number.  return true;} // Driver codepublic static void Main (String[] args){    int N = 100;    //check for every number from 1 to N      for(int i=1; i<=N; i++){      //check if current number is prime      if(isPrime(i)) {        Console.Write(i + " ");      }    }     }} // This code is contributed by Rajput-Ji
<script>// JavaScript program to display Prime numbers till N // function to check if a given number is primeconst isPrime = (n) => {     // since 0 and 1 is not prime return false.    if(n === 1||n === 0)return false;     // Run a loop from 2 to square root of n.    for(let i = 2; i <= Math.floor(Math.sqrt(n)); i++)    {           // if the number is divisible by i, then n is not a prime number.      if(n % i == 0)return false;    }         // otherwise, n is prime number.    return true;  }        // Driver code     let N = 100;     // check for every number from 1 to N  for(let i=1; i<=N; i++)  {         // check if current number is prime      if(isPrime(i)) {          document.write(i);      }  }     // This code is contributed by shinjanpatra  </script>
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)), Space Complexity: O(1)
You can further optimize the time complexity to O(n*log(log(n))). Check Sieve of Eratosthenes.
ankthon
Rajput-Ji
vishnusreddy
_saurabh_jaiswal
gabaa406
gsingh6122016
ukasp
singhdushyant260
shinjanpatra
subham348
Prime Number
Mathematical
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo Operator (%) in C/C++ with Examples
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
Program for factorial of a number
The Knight's tour problem | Backtracking-1
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
Euclidean algorithms (Basic and Extended)
Minimum number of jumps to reach end
How to swap two numbers without using a temporary variable?