OMP for循环条件不是简单的关系比较

OMP for loop condition not a simple relational comparison

我有这个程序由于 error: condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', '>=', or '!=') of loop variable 'i' 而无法编译,参考 for (size_t i = 2; i * i <= n; i++)。如何在不影响性能的情况下修改和修复它?这是由于旧的 OpenMP 版本导致的问题吗? (因为我记得以前在另一台旧版本的计算机上遇到过不同的问题,现在已经解决了。)

#include <iostream>
#include <cstdio>

int main(int argc, char **argv)
{
    if (argc != 2)
        return EXIT_FAILURE;
    size_t n;
    if (sscanf(argv[1], "%zu", &n) == 0)
        return EXIT_FAILURE;
    auto *prime = new size_t[n + 1];
    for (size_t i = 2; i <= n; i++)
        prime[i] = i;
    #pragma omp parallel for
    for (size_t i = 2; i * i <= n; i++)
        for (size_t j = i * i; j <= n; j += i)
            prime[j] = 0;
    size_t N = 0;
    for (size_t i = 2; i <= n; i++)
        if (prime[i] != 0)
            N++;
    std::cout << N << '\n';
}

#pragma omp parallel for 之后的循环必须是 canonical form 才能确认。在您的情况下,问题出在测试表达式上,它应该是以下之一:

var relational-op b
b relational-op var

因此,您必须使用@Yakk 的建议:计算 nsqrt 并将其与 i:

进行比较
const size_t max_i=sqrt(n);
#pragma omp parallel for
  for (size_t i = 2; i <= max_i; i++)
  ....