PAT B1013 数素数
- 思路1:
-code1:
#include <cstdio>
#include <math.h>
using namespace std;
const int maxn = 1000001;
int Prime[maxn];
bool P[maxn] = {0};
int PNum = 0;
void findPrime(int n){
for(int i = 2; i < maxn; ++i){
if(!P[i]){
Prime[PNum++] = i;
if(PNum > n) break;
for(int j = i + i; j < maxn; j += i){
P[j] = true;
}
}
}
}
int main(){
int M, N, count = 0;
scanf("%d%d", &M, &N);
findPrime(N);
for(int i = M; i <= N; ++i){
printf("%d", Prime[i-1]);
count++;
if(count % 10 != 0 && i < N) printf(" ");
else printf("\n");
}
return 0;
}
- TIPS:
- 注意输出格式!
- main里要调用findPrime
- >n的素数就不用计算了
- 小技巧:将空格换成#来看哪里格式出了问题
- maxn不能太小,否则有的样例过不了
- T2 code:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000010; //10^4是素数的个数
int prime[maxn];
bool p[maxn];
void GetPrime(int n){
int idex = 0;
for(int i = 2; i < maxn; ++i){
if(p[i] == false){
prime[idex++] = i;
if(idex > n) break;
for(int j = i + i; j < maxn; j += i){
p[j] = true;
}
}
}
}
int main(){
int lower, upper, cnt = 0;
scanf("%d %d", &lower, &upper);
GetPrime(upper);
for(int i = lower-1; i < upper; ++i){
printf("%d", prime[i]);
if(++cnt % 10 == 0) printf("\n");
else if(i < upper - 1) printf(" ");
}
return 0;
}
-
思路2:IsPrime();
-
code:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000010; //10^4是素数的个数
int prime[maxn];
bool IsPrime(int x){
if(x <= 1) return false;
int sqr = sqrt(1.0 * x);
for(int i = 2; i <= sqr; ++i){
if(x % i == 0) return false;
}
return true;
}
void GetPrime(int x){
int idex = 0;
for(int i = 0; i < maxn; ++i){
if(IsPrime(i)){
prime[idex++] = i;
if(idex > x) break;
}
}
}
int main(){
int lower, upper, cnt = 0;
scanf("%d %d", &lower, &upper);
GetPrime(upper);
for(int i = lower-1; i < upper; ++i){
printf("%d", prime[i]);
if(++cnt % 10 == 0) printf("\n");
else if(i < upper - 1) printf(" ");
}
return 0;
}