简单的素数三种算法_一般_约数_枚举_整数分解

  素数的判断有这三种比较一般的算法, 写起来代码也比较简洁、高效!

  //通常有着素数测试, 约数枚举, 以及整数分解

  

  下面我们直接上代码 : 

  

#include <iostream>
#include <cstdlib>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <queue>
#include <vector>
#include <string>
#include <list>
#include <map>
#include <stack>
#include <set>
using namespace std;

//简单的素数判断枚举
bool is_prime(int x){
    for(int i = 2; i * i <= x; i++){
        if(x % i == 0)  return false;
    }
    return n != 1;          //这个return 是真的灵魂, 同时进行特判
}
// vector 约数 , 从 1 - i * i <= n 循环, 然后 1 次放 2 个
vector<int> divisor(int x){
    vector<int> res;
    for(int i = 1; i * i <= n; i++){
        if(x % i == 0){
            res.push_back(i);
            if(i != x / i)  res.push_back(x / i);
        }
    }
    return res;
}
// map 因数分解, 注意是因数, 而不是约数, 这里有关于 map 的初级使用,而却因数不含 1 ;
map<int, int> prime_factor(int n){
    map<int , int>  res;
    for(int i = 2; i * i <= n; i++){
        while(n % i == 0){
            res[i]++;
            n /= i;
        }
    }
    if(n != 1)  res[n] = 1;
    return res;
}

int main()
{
    return 0;
}

 

posted @ 2019-09-02 15:36  lucky_light  阅读(1043)  评论(0编辑  收藏  举报