质数之试除法与质数筛



质数的定义

  • 对于小于等于 1 1 1 的数来说,都不是质数;
  • 对于大于 1 1 1 的数来说,因数只有 1 1 1 和它本身的数就称为质数。

原理

算数基本定理(唯一分解定理): 任何合数都可以分解为若干质数的乘积,且分解式唯一(不考虑顺序) 算数基本定理(唯一分解定理):\\ 任何合数都可以分解为若干质数的乘积,且分解式唯一(不考虑顺序) 算数基本定理(唯一分解定理):任何合数都可以分解为若干质数的乘积,且分解式唯一(不考虑顺序)


试除法判定质数

具体思路

  • 2 2 2 开始一个数一个数开始试,直到 s q r t ( n ) sqrt(n) sqrt(n),如果能整除中间某个数,就不是质数;反之则是。
  • 为什么是 s q r t ( n ) sqrt(n) sqrt(n)
    • 每一对因数都是成对出现的,我们可以枚举其中较小的那一个即可。

时间复杂度分析

O ( n ) O(\sqrt{n}) O(n )


AcWing 866. 试除法判定质数

题目链接:https://www.acwing.com/activity/content/problem/content/935/

试除法判断质因子


CODE

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int n;

bool isprime(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()
{
    cin >> n;
    while (n -- ){
        int a;
        scanf("%d", &a);
        
        if(isprime(a)) puts("Yes");
        else puts("No");
    }
}


分解质因数

原理

由前面的算术基本定理可知,每个数都可以分为若干质数的乘积形式。


思路

  • 2 2 2 开始除,当除到 k k k 时, n n n k k k 之前的所有质因子除过,如果 n n n 能被 k k k 整除,那么说明 k k k 一定是当前最小的质因子。
    • 8 8 8 举例:
    • 8 8 8 可以被 2 2 2 3 3 3 次,那么式子就是: 8 = 2 ∗ 2 ∗ 2 8 = 2 * 2 * 2 8=222
    • 如果说枚举到了 4 4 4 ,而 4 = 2 ∗ 2 4 = 2 * 2 4=22,那么 4 4 4 的倍数就是 2 2 2 的倍数,那么轮到 4 4 4 的时候公倍数早就被 2 2 2 除完了。

时间复杂度分析

O ( n ) O(\sqrt{n}) O(n )


AcWing 867. 分解质因数

题目链接:https://www.acwing.com/activity/content/problem/content/936/

分解质因数

CODE

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int n;

void divide(int x){
    for(int i = 2; i <= x / i; ++i){
        if(x % i == 0){
            int res = 0;
            
            while(x % i == 0){
                x /= i;
                res++;
            }
            
            printf("%d %d", i, res);
            puts("");
        }
    }
    
    if(x > 1) printf("%d %d\n", x, 1);
    puts("");
}

int main()
{
    cin >> n;
    
    while (n -- ){
        int a;
        scanf("%d", &a);
        
        divide(a);
    }
}

质数筛

质数筛详情可见:质数筛(记录)

AcWing 868. 筛质数

题目链接:https://www.acwing.com/activity/content/problem/content/937/
质数筛

CODE

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1e6 + 10;
int n;
int primes[N], cnt;
bool st[N];

void is_prime(){
    for(int i = 2; i <= n; ++i){
        if(!st[i]) primes[cnt++] = i;
        
        for(int j = 0; primes[j] <= n / i; ++j){
            st[i * primes[j]] = true;
            if(i % primes[j] == 0) break;
        }
    }
}

int main()
{
    cin >> n;
    
    is_prime();
    
    cout << cnt << endl;
}
  • 16
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值