1.给定n,求出1~n中质数的个数
可以先记一下结论
是一个数学界推出来的,不知道为什么,记住就行
1-N里面有N/lnN个质数
朴素筛法(埃氏)
思想是用每个质数去筛除以它为约数的合数。
每个质数都要做一遍。
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e6;
bool st[N]; //判断有没有被筛掉
int cnt = 0,primes[N];
void get_res(int x)
{
for(int i = 2;i<=x;i++)
{
if(!st[i])
{
primes[cnt ++ ] = i;
for(int j = i+i;j<=x;j+=i)st[j] = true;
}
}
cout<<cnt;
return;
}
int main()
{
int n;
cin>>n;
get_res(n);
return 0;
}
线性筛法
中心思想是确保每个数在整个过程中都只被他最小的一个质数所筛除,这样就减少了很多无谓的计算量
在1e7的数据量下,线性筛法比埃氏算法快一倍。
#include <iostream>
#include <algorithm>
using namespace std;
const int N= 1000010;
int primes[N], cnt; //这里记录每一个质数
bool st[N];
void get_primes(int n)
{
for (int i = 2; i <= n; i ++ )
{
if (!st[i]) primes[cnt ++ ] = i;
for (int j = 0; primes[j] <= n / i; j ++ )
//一个合数n最多到n/(它的质数)的时候就会被筛除,记住就行
{
st[primes[j] * i] = true;
//一个小于i的最小质数的数,也能确保它是primes[j] * i的最小质数
if (i % primes[j] == 0) break;
//找到i的最小质数,退出
}
}
}
int main()
{
int n;
cin >> n;
get_primes(n);
cout << cnt << endl;
return 0;
}
2.判定一个数是否是质数
朴素无华版:
思路是枚举比这个数小的每个数,看取余是否为0
#include <iostream>
#include <algorithm>
using namespace std;
int n;
bool is_prime(int x)
{
if(x == 1)return false;
for(int i = 2;i<x;i++)
{
if(!(x%i)) return false;
}
return true;
}
但是这样基本在所有平台都会超时的,因为你没有get到这道题要考的点
优化版:
其实我们只需要枚举到根号n就可以确定是不是质数,一个数n如果是合数,那么它的约数有两种情况:
1.两个数都等于根号n,例如9 = 3*3,再枚举比3大的也没有意义了。
2.一个大于根号n,一个小于根号n,例如8 = 2 * 4,我们只需要找到2就可以确认它是合数。
因此同学A想到了改良的方法:
#include <iostream>
#include <algorithm>
using namespace std;
int n;
bool is_prime(int x)
{
if(x == 1)return false;
for(int i = 2;i<=sqrt(x);i++)
{
if(!(x%i)) return false;
}
return true;
}
但是这样的话,我们又用到了sqrt()来求n的根号,其实sqrt()这个函数也很费时间,所以并不是很好的选择。
这时候又有同学b提出了一种做法:
#include <iostream>
#include <algorithm>
using namespace std;
int n;
bool is_prime(int x)
{
if(x == 1)return false;
for(int i = 2;i*i<=x;i++)
{
if(!(x%i)) return false;
}
return true;
}
这样确实增加了速度,但依旧会显示超时,这是为什么呢?
因为有些时候数据很大,有可能i*i这一项在一次循环后直接大于int的范围了(1e9),这样在计算机里面就会变成一个负数,于是就会影响运行结果,甚至一直循环下去。
于是我们找到了最好的一种写法:
#include <iostream>
#include <algorithm>
using namespace std;
int n;
bool is_prime(int x)
{
if(x == 1)return false;
for(int i = 2;i <= x / i;i++)
{
if(!(x%i)) return false;
}
return true;
}
这样就万无一失了。
3.分解一个数的质因数:
与上一种类型的题类似,我们利用同样的方法:
#include <iostream>
#include <algorithm>
using namespace std;
void get_prime(int n)
{
for(int i = 2; i<=n/i ; i++)
{
if(n%i == 0)
{
int cnt = 0; //记录每个质因子出现了多少此
while(n % i == 0) //循环对n进行操作
{
n/=i;
cnt++;
}
cout<<i<<' '<<cnt<<endl;
}
}
if(n>1)cout<<n<<' '<<1<<endl;
cout<<endl;
}
int main()
{
int n,x;
cin>>n;
while(n--){
cin>>x;
get_prime(x);
}
return 0;
}