130 likes | 764 Views
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
E N D
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. fori = 2, 3, 4, ..., √n : ifA[i] is true: forj = 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 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; } }