[AcWing 866] 试除法判定质数

image

试除法 复杂度 \(O(\sqrt{n})\)

总体复杂度 $100 \times \sqrt{2^{31}} \approx 4.6 \times 10^{6} $


点击查看代码
#include<iostream>

using namespace std;

bool is_prime(int n)
{
    if (n < 2)  return false;
    for (int i = 2; i <= n / i; i ++) {
        if (n % i == 0)
            return false;
    }
    return true;
}
int main()
{
    int n;
    cin >> n;
    while (n --) {
        int x;
        cin >> x;
        if (is_prime(x))    puts("Yes");
        else    puts("No");
    }
    return 0;
}

  1. 循环终止的条件用 i <= x / i 最好,原因如下:
    ① 如果使用 i <= sqrt( x ),每次循环都会使用 sqrt 函数计算,会产生时间开销;
    ② 如果使用 i * i <= x,i * i 容易造成溢出;
  2. x < 2 时直接返回 false;
posted @ 2022-05-07 23:48  wKingYu  阅读(40)  评论(0)    收藏  举报