【问题标题】:How to find loop invariant of Sieve of Eratosthenes Algorithm?如何找到埃拉托色尼筛算法的循环不变量?
【发布时间】:2020-12-02 09:56:32
【问题描述】:

谁能帮我制作 Eratosthenes 算法的循环不变量?

这里是和平的代码:

埃拉托色尼算法筛是 输入:一个整数 n > 1。 输出:从 2 到 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.

【问题讨论】:

    标签: algorithm sieve-of-eratosthenes loop-invariant


    【解决方案1】:

    ith 迭代之后,A[x] = false 用于所有 x <= n,其中 x 是任意整数 j 的倍数,因此 2 <= j <= i

    【讨论】:

    • 你能告诉我在这种情况下什么是循环不变量?
    • 这是不变量。这是一个在每次迭代后都保持的属性。如果将n 替换为i,则可以证明整个算法是正确的。
    【解决方案2】:

    你可以这样做

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 2011-12-16
      相关资源
      最近更新 更多