Finding Prime numbers - Sieve of Eratosthenes

mycodeschool · 314K views · 2013 · 9:54

Open on YouTube

Algorithms & data structuresEducation & learningtutorial

Why Stack Overflow recommends it

Stack Overflow users link it when answering questions about generating or counting many primes quickly, as a clear walkthrough of the sieve and its optimizations.

Recommended by 2 people across 2 different months, 2016 to 2020.

What it is

A short mycodeschool tutorial on the Sieve of Eratosthenes, the ancient algorithm for generating all small primes up to a few million. It walks through the idea and writes a simple prime generation program, following an earlier lesson on trial division.

What people said

Recommends amit · 2016-09 · Stack Overflow · on “How to generate huge amount of prime numbers in java?”

Memory is not an issue in your case. Array of size n = 3000000 can be defined inside the stack frame of a function. Actually array of size 10^8 can be defined safely inside a function. If you need more than that define it as a gloabal variable(Instance variable). Coming to your code there is an IndexOutOfBoundsException in your third code. You need to check for factors of a number only uptill sqrt(n) . Factors exist in pairs one factor <=sqrt(n) and other >=sqrt(n) . So you can optimize the sieve of Eratosthenes algorithm. Here is a link to one wonderful tutorial [this video] on various optimizations of sieve.

Recommends RICKY KUMAR · 2018-01 · Stack Overflow · on “Why is the first solution way much slower than the second one, to calculate the sum of prime numbers?”

You can refer [this video] it's like finding all primes quickly and then you can add them. You can also learn more about this kind of algorithm here [LINK]

Cites Emma Marcier · 2020-07 · Stack Overflow · on “Cant find the fix for my program at LeetCode Challenge of PrimeNumbers”

This'll also pass through: public class Solution { public static final int countPrimes(int n) { // mapping for if the number is divisible by prime numbers, which would make that number a composite number boolean[] notPrime = new boolean[n]; // counting prime numbers int count = 0; for (int i = 2; i < n; i++) { // If the index of notPrime would be false, we have a prime number, we go through the if, otherwise we continue if (notPrime[i] == false) { // Increment the number of prime numbers count++; // Look into future numbers for (int j = 2; i * j < n; j++) { // find composite numbers and set their indices to true notPrime[i * j] = true; } } } return count; } } References For additional detail