Sorting algorithms Sieve of Eratosthenes Dr. Szczepan Paszkiel Department of Electrical, Control & Computer Engineering Institute of Control & Computer Engineering Opole University of Technology
Sieve of Eratosthenes - pseudocode Input: an integer n > 1 Let A be an array of Boolean values, indexed by integers 2 to n, initially all set to true. for i = 2, 3, 4, ..., √n : if A[i] is true: for j = i2, i2+i, i2+2i, ..., n: A[j] := false Now all i such that A[i] is true are prime.
Sieve of Eratosthenes flowchart YES Sieve of Eratosthenes flowchart NO a[i] = true - prime number a[i] = false - composite number NO YES
Sieve of Eratosthenes in C++ for(int i = 2; i <= N; i++) a[i] = 1; max = (int)sqrt(N); for(i = 2; i <= max; i++) if(a[i]==1) { j = i + i; while(j <= N) a[j] = 0; j += i; }