0

Can anyone help me to make loop invarients of Eratosthenes Algorithm please?

Here is the peace of code:

algorithm Sieve of Eratosthenes is input: an integer n > 1. output: all prime numbers from 2 through n.

let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.

for i = 2, 3, 4, ..., not exceeding √n do
    if A[i] is true
        for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n do
            A[j] := false

return all i such that A[i] is true.

2 Answers2

1

After the ith iteration, A[x] = false for all x <= n where x is a multiple of any integer j such that 2 <= j <= i.

Mo B.
  • 5,307
  • 3
  • 25
  • 42
  • could you tell me what is the loop invariant in this case? – Salma Moujahid Dec 02 '20 at 10:41
  • This is the invariant. It's a property that holds after each iteration. If you subsitute `n` for `i`, you can then prove that the entire algorithm is correct. – Mo B. Dec 02 '20 at 11:13
0

You can do as

vector<int> getPrimes(int n) {

  vector<bool> A(n + 1, true);

  for (int i = 2; i * i <= n; i++) {
    for (int j = i * i; j <= n; j += i) {
      A[j] = false;
    }
  }

  vector<int> primes;

  for (int i = 2; i <= n; i++) {
    if (A[i]) {
      primes.push_back(i);
    }
  }

  return primes;
}
starboy_jb
  • 899
  • 1
  • 6
  • 13