Sieve of Eratosthenes - Prime numbers

Post Reply
User avatar
Pigeon
Posts: 18059
Joined: Thu Mar 31, 2011 3:00 pm

Sieve of Eratosthenes - Prime numbers

Post by Pigeon » Fri Sep 13, 2013 7:59 pm

Sieve of Eratosthenes

In mathematics, the sieve of Eratosthenes, one of a number of prime number sieves, is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2.

The multiples of a given prime are generated as a sequence of numbers starting from that prime, with constant difference between them which is equal to that prime. This is the sieve's key distinction from using trial division to sequentially test each candidate number for divisibility by each prime.

The sieve of Eratosthenes is one of the most efficient ways to find all of the smaller primes (below 10 million or so). It is named after Eratosthenes of Cyrene, a Greek mathematician; although none of his works have survived, the sieve was described and attributed to Eratosthenes in the Introduction to Arithmetic by Nicomachus.

Algorithm description

A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself.

To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method:
  • Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n).
  • Initially, let p equal 2, the first prime number.
  • Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. These will be multiples of p: 2p, 3p, 4p, etc.; note that some of them may have already been marked.
  • Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
  • When the algorithm terminates, all the numbers in the list that are not marked are prime.
The main idea here is that every value for p is prime, because we have already marked all the multiples of the numbers less than p.

Image

User avatar
Pigeon
Posts: 18059
Joined: Thu Mar 31, 2011 3:00 pm

Re: Sieve of Eratosthenes

Post by Pigeon » Fri Sep 13, 2013 8:22 pm

But one can also determine if a number is prime quite quickly.

If the modulo, using the prime, of a number raised to the power of the prime minus 1 is equal to 1, it is prime.

a = 2
p = 7 (The number to test for prime)

a^p-1 mod p = 1

2^7-1 mod 7

2^6 mod 7

64 mod 7 = 1

(64 - (9*7)) = 1

Post Reply