素数相关知识

下列程序

1、素数的判断

2、找x的约数

3、找x的质因数

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <vector>
 4 #include <map>
 5 #define READ() freopen("in.txt", "r", stdin);
 6 using namespace std;
 7 
 8 //以下做法都是O(n^1/2)
 9 bool isPrime(int x)//判断素数
10 {
11     for (int i = 2; i*i <= x; i++)
12     {
13         if(x % i == 0) return false;
14     }
15     return x == 1;//1 是特殊情况
16 }
17 vector<int> divisor(int x)//枚举x的约数
18 {
19     vector<int> res;
20     for (int i = 1; i*i <= x; i++)
21     {
22         if (x % i == 0)
23         {
24             res.push_back(i);
25             if (i != x / i) res.push_back(x / i);
26         }
27     }
28     return res;
29 }
30 map<int,int> prime_factor(int x)//质因数分解
31 {
32     map<int, int> res;
33     for (int i = 2; i*i <= x; i++)
34     {
35         while (x % i == 0)
36         {
37             res[i]++;
38             x /= i;
39         }
40     }
41     if (x != 1) res[x]++;//最后一个质因子
42     return res;
43 }
44 
45 
46 int main()
47 {
48     READ()
49     int x;
50     while(~scanf("%d", &x))
51     {
52         if (isPrime(x)) cout << "yes" << endl;
53         else cout << "no" << endl;
54         vector<int> v = divisor(x);
55         for (int i = 0; i < v.size(); i++) cout << v[i] << endl;
56         map<int,int> m = prime_factor(x);
57         map<int,int> :: iterator it;
58         for (it = m.begin(); it != m.end(); it++) cout << (*it).first << ":" << (*it).second << endl;
59         cout << endl << endl;
60     }
61     return 0;
62 }

4、艾氏筛法

筛出1..n的素数 思路

确定基准为2 那么从3 到n 去掉所有2的倍数

确定基准为3 那么从4 到n 去掉所有3的倍数

确定基准为下一个剩下的数a 从a到n 去掉所有 a的倍数 直到n 边筛选完毕

 1 #include <iostream>
 2 #include <string.h>
 3 #include <stdio.h>
 4 #define MAXN 99997
 5 using namespace std;
 6 //艾氏筛法 因为cb不是英语不能调试
 7 
 8 bool prime[MAXN];
 9 
10 void getPrime(int n)
11 {
12     for (int i = 2; i <= n; i++)
13     {
14         for (int j = 2; j*i <= n; j++)
15         {
16             prime[i*j] = false;
17         }
18     }
19 
20 }
21 int main()
22 {
23     memset(prime, 1, sizeof(prime));
24     prime[0] = prime[1] = false;
25     int n;
26     cin >> n;
27     getPrime(n);
28     int j = 0;
29     while (cin >> j)
30     {
31         if (prime[j]) cout << "yes" << endl;
32         else cout << "no" << endl;
33     }
34     return 0;
35 }
原文地址:https://www.cnblogs.com/oscar-cnblogs/p/6435250.html