求出一位的質數,存進vector_1中,再分別利用vector_1中的數做爲首位數求兩位質數,存入vector_2,依次求出位數爲n的質數,存進vector_n,打印時只需打印vector_n中的數字便可。ios
/* ID:jzzlee1 PROG:sprime LANG:C++ */ #include<iostream> #include<fstream> #include<cstring> #include<vector> #include<cmath> using namespace std; ifstream fin("sprime.in"); ofstream fout("sprime.out"); bool check(int p) //檢測是否質數 { for(int i=2;i<=(int)sqrtf(p);i++) if(p%i==0) return 0; return 1; } int main() { int n; fin>>n; //cin>>n; vector<int> vec1,vec2,vec3,vec4,vec5,vec6,vec7,vec8; int i=0;int d;int p; vec1.push_back(2); vec1.push_back(3); vec1.push_back(5); vec1.push_back(7); vector<int>::iterator iter; if(n>1) //兩位數 { for(iter=vec1.begin();iter!=vec1.end();++iter) for(d=1;d<=9;d+=2) { p=10*(*iter)+d; if(check(p)) vec2.push_back(p); } } if(n>2) //三位數 { for(iter=vec2.begin();iter!=vec2.end();++iter) for(d=1;d<=9;d+=2) { p=10*(*iter)+d; if(check(p)) vec3.push_back(p); } } if(n>3) //四位數 { for(iter=vec3.begin();iter!=vec3.end();++iter) for(d=1;d<=9;d+=2) { p=10*(*iter)+d; if(check(p)) vec4.push_back(p); } } if(n>4) //五位數 { for(iter=vec4.begin();iter!=vec4.end();++iter) for(d=1;d<=9;d+=2) { p=10*(*iter)+d; if(check(p)) vec5.push_back(p); } } if(n>5) //六位數 { for(iter=vec5.begin();iter!=vec5.end();++iter) for(d=1;d<=9;d+=2) { p=10*(*iter)+d; if(check(p)) vec6.push_back(p); } } if(n>6) //七位數 { for(iter=vec6.begin();iter!=vec6.end();++iter) for(d=1;d<=9;d+=2) { p=10*(*iter)+d; if(check(p)) vec7.push_back(p); } } if(n>7) //八位數 { for(iter=vec7.begin();iter!=vec7.end();++iter) for(d=1;d<=9;d+=2) { p=10*(*iter)+d; if(check(p)) vec8.push_back(p); } } switch(n) { case 1: { for(iter=vec1.begin();iter!=vec1.end();++iter) fout<<*iter<<endl; //cout<<*iter<<endl; break; } case 2: { for(iter=vec2.begin();iter!=vec2.end();++iter) fout<<*iter<<endl; //cout<<*iter<<endl; break; } case 3: { for(iter=vec3.begin();iter!=vec3.end();++iter) fout<<*iter<<endl; //cout<<*iter<<endl; break; } case 4: { for(iter=vec4.begin();iter!=vec4.end();++iter) fout<<*iter<<endl; //cout<<*iter<<endl; break; } case 5: { for(iter=vec5.begin();iter!=vec5.end();++iter) fout<<*iter<<endl; //cout<<*iter<<endl; break; } case 6: { for(iter=vec6.begin();iter!=vec6.end();++iter) fout<<*iter<<endl; //cout<<*iter<<endl; break; } case 7: { for(iter=vec7.begin();iter!=vec7.end();++iter) fout<<*iter<<endl; //cout<<*iter<<endl; break; } case 8: { for(iter=vec8.begin();iter!=vec8.end();++iter) fout<<*iter<<endl; //cout<<*iter<<endl; break; } } return 0; }