Sieve of Eratosthenes - GeeksforGeeks (2024)

Table of Contents
C++ C Java C# Javascript PHP Python3

Last Updated : 06 Mar, 2024

Improve

Improve

Like Article

Like

Save

Report

Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.

Example:

Input : n =10
Output : 2 3 5 7

Input : n = 20
Output: 2 3 5 7 11 13 17 19

The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so.

Recommended Problem

Techfest and the Queue

Solve Problem

Following is the algorithm to find all the prime numbers less than or equal to a given integernby the Eratosthene’s method:
When the algorithm terminates, all the numbers in the list that are not marked are prime.

Explanation with Example:

Let us take an example when n = 100. So, we need to print all prime numbers smaller than or equal to 100.

We create a list of all numbers from 2 to 100.

Sieve of Eratosthenes - GeeksforGeeks (1)

According to the algorithm we will mark all the numbers which are divisible by 2 and are greater than or equal to the square of it.

Sieve of Eratosthenes - GeeksforGeeks (2)

Now we move to our next unmarked number 3 and mark all the numbers which are multiples of 3 and are greater than or equal to the square of it.

Sieve of Eratosthenes - GeeksforGeeks (3)

We move to our next unmarked number 5 and mark all multiples of 5 and are greater than or equal to the square of it.

Sieve of Eratosthenes - GeeksforGeeks (4)

We move to our next unmarked number 7 and mark all multiples of 7 and are greater than or equal to the square of it.

Sieve of Eratosthenes - GeeksforGeeks (5)

We continue this process, and our final table will look like below:

Sieve of Eratosthenes - GeeksforGeeks (6)

So, the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89 and 97.

Implementation:

C++

// C++ program to print all primes smaller than or equal to

// n using Sieve of Eratosthenes

#include <bits/stdc++.h>

using namespace std;

void SieveOfEratosthenes(int n)

{

// Create a boolean array "prime[0..n]" and initialize

// all entries it as true. A value in prime[i] will

// finally be false if i is Not a prime, else true.

bool prime[n + 1];

memset(prime, true, sizeof(prime));

for (int p = 2; p * p <= n; p++) {

// If prime[p] is not changed, then it is a prime

if (prime[p] == true) {

// Update all multiples of p greater than or

// equal to the square of it numbers which are

// multiple of p and are less than p^2 are

// already been marked.

for (int i = p * p; i <= n; i += p)

prime[i] = false;

}

}

// Print all prime numbers

for (int p = 2; p <= n; p++)

if (prime[p])

cout << p << " ";

}

// Driver Code

int main()

{

int n = 30;

cout << "Following are the prime numbers smaller "

<< " than or equal to " << n << endl;

SieveOfEratosthenes(n);

return 0;

}

C

// C program to print all primes smaller than or equal to

// n using Sieve of Eratosthenes

#include <stdio.h>

#include <stdbool.h>

#include <string.h>

void SieveOfEratosthenes(int n)

{

// Create a boolean array "prime[0..n]" and initialize

// all entries it as true. A value in prime[i] will

// finally be false if i is Not a prime, else true.

bool prime[n + 1];

memset(prime, true, sizeof(prime));

for (int p = 2; p * p <= n; p++) {

// If prime[p] is not changed, then it is a prime

if (prime[p] == true) {

// Update all multiples of p greater than or

// equal to the square of it numbers which are

// multiple of p and are less than p^2 are

// already been marked.

for (int i = p * p; i <= n; i += p)

prime[i] = false;

}

}

// Print all prime numbers

for (int p = 2; p <= n; p++)

if (prime[p])

printf("%d ",p);

}

// Driver Code

int main()

{

int n = 30;

printf("Following are the prime numbers smaller than or equal to %d \n", n);

SieveOfEratosthenes(n);

return 0;

}

// This code is contributed by Aditya Kumar (adityakumar129)

Java

// Java program to print all primes smaller than or equal to

// n using Sieve of Eratosthenes

class SieveOfEratosthenes {

void sieveOfEratosthenes(int n)

{

// Create a boolean array "prime[0..n]" and

// initialize all entries it as true. A value in

// prime[i] will finally be false if i is Not a

// prime, else true.

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] is not changed, then it is a

// prime

if (prime[p] == true) {

// Update all multiples of p greater than or

// equal to the square of it numbers which

// are multiple of p and are less than p^2

// are already been marked.

for (int i = p * p; i <= n; i += p)

prime[i] = false;

}

}

// Print all prime numbers

for (int i = 2; i <= n; i++) {

if (prime[i] == true)

System.out.print(i + " ");

}

}

// Driver Code

public static void main(String args[])

{

int n = 30;

System.out.print("Following are the prime numbers ");

System.out.println("smaller than or equal to " + n);

SieveOfEratosthenes g = new SieveOfEratosthenes();

g.sieveOfEratosthenes(n);

}

}

// This code is contributed by Aditya Kumar (adityakumar129)

C#

// C# program to print all primes

// smaller than or equal to n

// using Sieve of Eratosthenes

using System;

namespace prime {

public class GFG {

public static void SieveOfEratosthenes(int n)

{

// Create a boolean array

// "prime[0..n]" and

// initialize all entries

// it as true. A value in

// prime[i] will finally be

// false if i is Not a

// prime, else true.

bool[] prime = new bool[n + 1];

for (int i = 0; i <= n; i++)

prime[i] = true;

for (int p = 2; p * p <= n; p++)

{

// If prime[p] is not changed,

// then it is a prime

if (prime[p] == true)

{

// Update all multiples of p

for (int i = p * p; i <= n; i += p)

prime[i] = false;

}

}

// Print all prime numbers

for (int i = 2; i <= n; i++)

{

if (prime[i] == true)

Console.Write(i + " ");

}

}

// Driver Code

public static void Main()

{

int n = 30;

Console.WriteLine(

"Following are the prime numbers");

Console.WriteLine("smaller than or equal to " + n);

SieveOfEratosthenes(n);

}

}

}

// This code is contributed by Sam007.

Javascript

<script>

// javascript program to print all

// primes smaller than or equal to

// n using Sieve of Eratosthenes

function sieveOfEratosthenes(n)

{

// Create a boolean array

// "prime[0..n]" and

// initialize all entries

// it as true. A value in

// prime[i] will finally be

// false if i is Not a

// prime, else true.

prime = Array.from({length: n+1}, (_, i) => true);

for (p = 2; p * p <= n; p++)

{

// If prime[p] is not changed, then it is a

// prime

if (prime[p] == true)

{

// Update all multiples of p

for (i = p * p; i <= n; i += p)

prime[i] = false;

}

}

// Print all prime numbers

for (i = 2; i <= n; i++)

{

if (prime[i] == true)

document.write(i + " ");

}

}

// Driver Code

var n = 30;

document.write(

"Following are the prime numbers ");

document.write("smaller than or equal to " + n+"<br>");

sieveOfEratosthenes(n);

// This code is contributed by 29AjayKumar

</script>

PHP

<?php

// php program to print all primes smaller

// than or equal to n using Sieve of

// Eratosthenes

function SieveOfEratosthenes($n)

{

// Create a boolean array "prime[0..n]"

// and initialize all entries it as true.

// A value in prime[i] will finally be

// false if i is Not a prime, else true.

$prime = array_fill(0, $n+1, true);

for ($p = 2; $p*$p <= $n; $p++)

{

// If prime[p] is not changed,

// then it is a prime

if ($prime[$p] == true)

{

// Update all multiples of p

for ($i = $p*$p; $i <= $n; $i += $p)

$prime[$i] = false;

}

}

// Print all prime numbers

for ($p = 2; $p <= $n; $p++)

if ($prime[$p])

echo $p." ";

}

// Driver Code

$n = 30;

echo "Following are the prime numbers "

."smaller than or equal to " .$n."\n" ;

SieveOfEratosthenes($n);

// This code is contributed by mits

?>

Python3

# Python program to print all

# primes smaller than or equal to

# n using Sieve of Eratosthenes

def SieveOfEratosthenes(n):

# Create a boolean array

# "prime[0..n]" and initialize

# all entries it as true.

# A value in prime[i] will

# finally be false if i is

# Not a prime, else true.

prime = [True for i in range(n+1)]

p = 2

while (p * p <= n):

# If prime[p] is not

# changed, then it is a prime

if (prime[p] == True):

# Update all multiples of p

for i in range(p * p, n+1, p):

prime[i] = False

p += 1

# Print all prime numbers

for p in range(2, n+1):

if prime[p]:

print(p)

# Driver code

if __name__ == '__main__':

n = 20

print("Following are the prime numbers smaller"),

print("than or equal to", n)

SieveOfEratosthenes(n)

Output

Following are the prime numbers smaller than or equal to 302 3 5 7 11 13 17 19 23 29 

Time Complexity: O(N*log(log(N)))
Auxiliary Space: O(N)

You may also like to see:

  • How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
  • Segmented Sieve.
  • Sieve of Eratosthenes in O(n) time complexity


`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Sieve of Eratosthenes - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Corie Satterfield

Last Updated:

Views: 6623

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Corie Satterfield

Birthday: 1992-08-19

Address: 850 Benjamin Bridge, Dickinsonchester, CO 68572-0542

Phone: +26813599986666

Job: Sales Manager

Hobby: Table tennis, Soapmaking, Flower arranging, amateur radio, Rock climbing, scrapbook, Horseback riding

Introduction: My name is Corie Satterfield, I am a fancy, perfect, spotless, quaint, fantastic, funny, lucky person who loves writing and wants to share my knowledge and understanding with you.