试除法判定质数算法总结

知识概览

质数的定义

在大于1的整数中,如果只包含1和本身这两个约数,就被称为质数,或者叫素数。

质数的判定------试除法

暴力算法 时间复杂度

改进算法 时间复杂度

暴力算法:时间复杂度O(n)

算法模版

cpp 复制代码
bool is_prime(int n)
{
    if (n < 2) return false;
    for (int i = 2; i < n; i++)
        if (n % i == 0)
            return false;
    return true;
}

优化算法:时间复杂度O(sqrt(n))

算法模版

cpp 复制代码
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;
}

例题展示

题目链接

活动 - AcWing系统讲解常用算法与数据结构,给出相应代码模板,并会布置、讲解相应的基础算法题目。https://www.acwing.com/problem/content/868/

题解

用试除法的改进版本可以解决,否则会超时。

代码

cpp 复制代码
#include <iostream>
#include <algorithm>

using namespace std;

bool is_prime(int x)
{
    if (x < 2) return false;
    for (int i = 2; i <= x / i; i++)
        if (x % 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. AcWing算法基础课
相关推荐
复杂网络与机器学习17 小时前
数学建模七件武器:把现实翻译成能算的模型,再证明它靠得住
数学·开源
lisw0517 小时前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
一起学安全技术18 小时前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs19 小时前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信1504130575920 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
GoAI1 天前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi1 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵
choumou_M1 天前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法
Coder_Shenshen1 天前
罗克韦尔ACD工程归档离线变量树解析
算法·c#