2404 Super Prime(欧拉筛素数)
Problem Description
We all know, prime is a kind of special number which has no other factors except of 1 and itself.
2,3,5,7,11,13,17,19,23,29 are the top 20 primes.
Now there is a new question about prime:
We call a prime as super prime when and only when which can be represented as the sum of multiple continuous primes. For example: 5=2+3, so 5 is a super prime.
Please program to judge whether a number is a super prime or not.
Input
The first line is an integer T (T<=1000), and then T lines follow.
There is only one positive integer N(1
Output
For each case you should output the case number first, and then the word “yes” if the integer N is a super prime, and you should output “no” otherwise.
Sample Input
3
5
7
8
Sample Output
Case 1: yes
Case 2: no
Case 3: no
#include<iostream>
#include<algorithm>
#include<memory.h>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
const int M=100000;
int prim[M];
bool vis[M];
int prime(int n) {//欧拉筛素数O(n)
int cnt=0;
memset(vis,0,sizeof(vis));
for(int i=2; i<n; i++) {
if(!vis[i]) {
prim[cnt++]=i;
}
for(int j=0; j<cnt&&i*prim[j]<n; j++) {
vis[i*prim[j]]=1;
if(i%prim[j]==0) {
break;
}
}
}
return cnt;
}
int look(int num,int tol) {//二分查找
int mid=0;
int low=0;
int high=num;
while(low<high) {
mid=(low+high)/2;
if(tol==prim[mid]) {
return mid;
} else if(tol<prim[mid]) {
high=mid;
} else if(tol>prim[mid]) {
low=mid+1;
}
}
return -1;
}
int main() {
int n;
cin>>n;
int x;
int num=prime(M);
for(int i=1; i<=n; i++) {
cin>>x;
cout<<"Case "<<i<<": ";
int flag=0;
int inx=look(num,x);
/*for(int j=0;j<num;j++){//线性查找也可以A
if(prim[j]==x){
flag=1;
inx=j;
break;
}
}*/
if(inx!=-1) {
int flags=0;
for(int j=0; j<inx; j++) {//连续的几个质数相加,这个很重要
int sum=0;
for(int k=j;k<inx;k++){
sum+=prim[k];
if(sum>x){
break;
}
else if(sum==x){
flags=1;
break;
}
}
if(flags==1){
break;
}
}
if(flags==0) {
cout<<"no"<<endl;
} else {
cout<<"yes"<<endl;
}
}
else {
cout<<"no"<<endl;
}
}
return 0;
}
/***************************************************
User name: dlili
Result: Accepted
Take time: 76ms
Take Memory: 344KB
Submit time: 2018-04-13 10:29:22
****************************************************/