Articles

2.1: The Sieve of Eratosthenes


A prime is an integer greater than 1 that is only divisible by 1 and itself. The integers 2, 3, 5, 7, 11 are prime integers. Note that any integer greater than 1 that is not prime is said to be a composite number.

The Sieve of Eratosthenes

The Sieve of Eratosthenes is an ancient method of finding prime numbers up to a specified integer. There are several other methods used to determine whether a number is prime or composite. We first present a lemma that will be needed in the proof of several theorems.

Every integer greater than one has a prime divisor.

We present the proof of this Lemma by contradiction. Suppose that there is an integer greater than one that has no prime divisors. Since the set of integers with elements greater than one with no prime divisors is nonempty, then by the well ordering principle there is a least positive integer (n) greater than one that has no prime divisors. Thus (n) is composite since (n) divides (n). Hence [n=ab mbox{with} 1

If (n) is a composite integer, then n has a prime factor not exceeding (sqrt{n}).

Since (n) is composite, then (n=ab), where (a) and (b) are integers with (1sqrt{n}), then

[sqrt{n}

and as a result

[ab>sqrt{n}sqrt{n}=n.]

Therefore (aleq sqrt{n}). Also, by Lemma 3, (a) must have a prime divisor (a_1) which is also a prime divisor of (n) and thus this divisor is less than (a_1 leq aleq sqrt{n}).

We now present the algorithm of the Sieve of Eratosthenes that is used to determine prime numbers up to a given integer.

The Algorithm of the Sieve of Eratosthenes

  1. Write a list of numbers from 2 to the largest number (n) you want to test. Note that every composite integer less than (n) must have a prime factor less than (sqrt{n}). Hence you need to strike off the multiples of the primes that are less than (sqrt{n})
  2. Strike off all multiples of 2 greater than 2 from the list . The first remaining number in the list is a prime number.
  3. Strike off all multiples of this number from the list.
  4. Repeat the above steps until no more multiples are found of the prime integers that are less than (sqrt{n})

Exercises

  1. Use the Sieve of Eratosthenes to find all primes less than 100.
  2. Use the Sieve of Eratosthenes to find all primes less than 200.
  3. Show that no integer of the form (a^3+1) is a prime except for (2=1^3+1).
  4. Show that if (2^n-1) is prime, then (n) is prime.
    Hint: Use the identity ((a^{kl}-1)=(a^{k}-1)(a^{k(l-1)}+a^{k(l-2)}+...+a^k+1)).

Time Complexity: Sieve of Eratosthenes

When we try to make a hashing function (please refer it in Java Hashing Function), we need to use one prime as the base of hashing function to avoid from being collided. Although there are three methods which can be used to generate a prime number. But, Sieve of Eratosthenes among these prime functions is a very popular and simple algorithm.

Sieve of Eratosthenes’s concept is to remove all impossible multiples, the steps as:

  1. Remove the numbers multiple of 2
  2. Remove the numbers multiple of 3
  3. Remove the numbers multiple of 5

Algorithm (Sieve of Eratosthenes):Assume that array a contains the numbers’ boolean from 1 to n. Please list all the prime numbers up to n. The algorithm time complexity is O(nloglogn).

Analysis:At first, we should know time complexity of Harmonic Series is O(logn). Now, analyze the sieve of eratosthenes.

The inner loop can be expr e ssed by:
j=2, the inner loop will be executed → upper bound is (n/2) times
j=9, the inner loop will be executed → upper bound is (n/3) times
j=25, the inner loop will be executed → upper bound is (n/5) times

j=n, the inner loop will be executed → upper bound is 1 times

The above series time complexity is less than harmonic series: n/2 + n/4 + ..+ 1 → n (1/2 + 1/3 + 1/4 + … 1/n), according to harmonic series and Big-O, we can conclude the inner loop time complexity is O(logn). But, as we know, the algorithm shown above, it will sieve some numbers before execution. Hence, the run loop times should be n (1/2 + 1/3 + 1/5 + 1/7 + 1/ 11 + 1/13 + …). That is why, in some article, the time complexity is defined in O(loglogn). (The p is prime in the following equation)


The Sieve of Eratosthenes

Eratosthenes was the third librarian of the famous library in Alexandria and an outstanding scholar. The Sieve of Eratosthenes is an algorithm for collecting prime numbers, the invention of which he is credited with. Further details may be found at the Wikipedia link for Eratosthenes (http://en.wikipedia.org/wiki/Eratosthenes).

The Algorithm works as follows :

To collect all Prime numbers below a certain number (say N) start by first identifying all composite numbers and removing them from a predefined numerical sequence ( 1 to N ). Thus, whatever remains are all prime numbers.

The identification of Composite numbers is done by iteratively finding the multiples of all numbers from 2 (1 is not a prime number) till the maximum limit and removing the composite numbers at each step.

I.e, All multiples of 2 (excluding 2 itself) are removed. The next available number is found. In this case it is 3.

Then All multiples of 3 (excluding 3 itself) are removed. The next available number is found. In this case it is 5.

Then All multiples of 5 (excluding 5 itself) are removed. The next available number is found. In this case it is 7.

And so on till the maximum limit is reached.

I attempt here to provide an SAP implementation of the Sieve of Eratosthenes.

DATA : var type i, max type i,

temp type i, count type i value 2,

t_prime type table of i, wa_prime type i.

SELECTION-SCREEN begin of block b1 with frame.

SELECTION-SCREEN end of block b1.

DELETE t_prime from 1 to 1.

DELETE t_prime where table_line = temp.

READ TABLE t_prime into wa_prime with key table_line = var.

READ TABLE t_prime into var index var.

LOOP AT t_prime into wa_prime.

An execution of the above program has yielded accurate results finding all prime numbers upto 30,000.

I am sure that this may be optimized further, in terms of logic as well as implementation.

However, I have attempted to remain true to the original Algorithm of the Sieve of Eratosthenes.


To help you better understand prime numbers, we are going to explain an exercise.

Sara has 6 pieces of candy that she wants to share, but she doesn’t know how many people she can share them with so that everyone gets the same amount and none are leftover. How many ways can she do this?

Here is Sara and her 6 pieces of candy:

The first and easiest way is to give them to one person, in other words, divide by 1. This way that person will have 6 pieces of candy.

The next possibility is to divide them between 2 people. Since 6 divided by 2 is 3, each person gets 3 pieces of candy!

We are going to continue with the next number, 3. If we divide 6 pieces of candy between 3 people it is also an exact division and each person will get 2 pieces of candy:

Let’s continue with the numbers. We do not have exact divisions with 4 and 5, but we do with 6.

Since 6 divided by 6 is 1, we can give 6 children 1 piece of candy each.

We’re going to collect some information. We have 6 pieces of candy that we can share (with an exact division) between 1, 2, 3, and 6 people. In other words, we can divide the number 6 and get 0 as a remainder when we divide it by 1, 2, 3, and 6. These numbers are known as the divisors of 6.

We are going to try with another number, 7 for example.

Now Sara has 7 pieces of candy and wants to share them, but doesn’t know how many people she can share them with so that everyone gets the same amount and none are leftover. How many ways can she do this?

Henry is so lucky! He got all of the pieces of candy!

Are there other ways to do it? We cannot divide 7 by 2, 3, 4, 5, or 6, …but 7 is possible!

Sara can share the pieces of candy between 7 people, giving them one piece each:

So 7 can only be divided by 1 and 7, its only divisors are 1 and 7. These are the types of numbers we call prime numbers.

Are there more prime numbers? Of course! Let’s look for some more:

  • Is 4? No! Because its divisors are 1, 2, and 4.
  • Is 5? Yes! Because its divisors are 1 and 5.
  • Is 8? No! Because its divisors are 1, 2, 4, and 8.

In short, a number is prime if it only has 2 divisors: 1 and itself.

Now you can search for lots of prime numbers!


Initially, each number is assumed to be prime, i.e. all elements of isPrime are set to 1 . Then all multiples of i need to be set to 0 . A final scan over the array counts the number of primes.

My first attempt was based on a bool array instead of char , true instead of 1 and false instead of 0 . Even though bool s were more intuitive, they were a bit slower (&approx7%) because the final scan contained a branch which often flushed the CPU pipeline after a mis-prediction.

Both data types use 1 byte per element. Moreover, true is by default internally represented as 1 and false is internally represented as 0 . That means, the binary code generated by the C++ compiler for isPrime is identical for bool and char - except for the more efficient final scan of char .

Time for lastNumber = 1 billion: 13.5 seconds


2.1: The Sieve of Eratosthenes

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

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 (Ref Wiki).

Explanation with Example:
Let us take an example when n = 50. So we need to print all prime numbers smaller than or equal to 50.
We create a list of all numbers from 2 to 50.

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.

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.

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.

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

So the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47.
Thanks to Krishan Kumar for providing above explanation.
Implementation:
Following is the implementation of the above algorithm. In the following implementation, a boolean array arr[] of size n is used to mark multiples of prime numbers.


Contents

Divisibility

A prime number is only divisible by one or itself, so a number is prime if and only if is not divisible by any integer greater than and less than . One only needs to check integers up to because dividing larger numbers would result in a quotient smaller than .

Modular Arithmetic

Modular arithmetic can help determine if a number is not prime.

  • If a number not equal to is congruent to , then the number is not prime.
  • If a number not equal to ends with an even digit or , then the number is not prime.

Sieve of Eratosthenes

The Sieve of Eratosthenes is a relatively simplistic algorithm for generating a list of the first few prime numbers. It is a method in which the multiples of all known primes are labeled as composites, and subsequently crossed out, starting with multiples of two, then three, then five, and so on. For example, circle 2, and cross out all other multiples of two. Then circle 3, and cross out all multiples of three. Repeat with all other prime numbers as needed. Although simple to understand, it is inefficient for finding large primes.

Sieve of Sundaram

The Sieve of Sundaram is a relatively simplistic algorithm for generating all odd prime numbers, less than . It is a method by which all indices such that has a non trivial factor are struck out. It employs the fact that and if this is a non-trivial factorization.


Working Using Example

Step:1

Create a memory wich containing numbers from 2 to N(Here we take 100).

Step:2

Mark all the multiples of the first unmark number in the memory which is 2.

Step:3

Now mark all the multiples next unmarked number which is 3 in the memory.

Step:4

Move to the next unmark number which is 5. Now mark all the multiples of 5.

Step:5

Move to the next unmarked number which is our last unmarked number in range 2 to the square root of N.

Step:6

All the remaining unmarked numbers are our prime numbers.

Prime Numbers: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 41, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97.


Main implementation

To save additional space and time, at the cost of some additional complexity, we choose not to represent even integers in our sieve. Instead, the element at index k will indicate the primarily of the number 2k + 3 . We abstract this complexity away by wrapping BitSet in a class exposing special indexer methods:

The standard library classes BitSet, List, and ArrayList are imported for convenience in later use:

The sieve itself begins by creating a sieve array and then searching for the first zero entry. All odd multiples of this entry are set to true to indicate that they are composite. We start with the square i*i of i , because all multiples of i smaller than that will have already been set to true while dealing with smaller primes. Note that by default a BitSet is initialized to all zeros, as the algorithm requires.

When we're done, we iterate through the sieve, forming an ArrayList of elements still set to false, which we return:


Omega function

omega( k ) (or ω ( k )) is defined as the number of distinct prime factors that k has.

k omega( k )
00
10
21
31
41
51
62
71
81
91
102
111
122
131
142
152
161
171
182
191
202
212
222
231
242
251
262
271
282
291
303

Note that for a given m , the smallest k such that omega( k ) = m is given by k = primorial( m ). Furthermore the function grows rather slowly, because omega( k ) ≤ log2( k ).


Watch the video: Σπαστήρας Καρυδιών ΣΚ-200 (November 2021).