这个题目开始真正用C++了,因为,数组的分配有限制了,只好用c++中的vector:
/* ID: qq104801 LANG: C++ TASK: sprime */ #include <iostream> #include <cstdio> #include <string> #include <cstring> #include <vector> #include <map> #include <set> #include <algorithm> #include <cstdlib> #include <cmath> using namespace std; vector<vector<int> > p(9); int n; int isprime(int x) { if (x%2==0)return 0; for(int i=3;i*i<=x;i+=2) if(x%i==0)return 0; return 1; } void test() { freopen("sprime.in","r",stdin); freopen("sprime.out","w",stdout); cin>>n; //cout<<n<<endl; p[1].push_back(2); p[1].push_back(3); p[1].push_back(5); p[1].push_back(7); for(int i=2;i<=n;i++) { for(int j=0;j<p[i-1].size();j++) { long long num=p[i-1][j]*10; long long k; for(k=num+1;k<=num+9;k+=2) if(isprime(k))p[i].push_back(k); } } for(int i=0;i<p[n].size();i++) cout<<p[n][i]<<endl; } int main () { test(); return 0; }
看看测试结果:
USER: cn tom [qq104801] TASK: sprime LANG: C++ Compiling... Compile: OK Executing... Test 1: TEST OK [0.008 secs, 3508 KB] Test 2: TEST OK [0.003 secs, 3508 KB] Test 3: TEST OK [0.008 secs, 3508 KB] Test 4: TEST OK [0.008 secs, 3508 KB] Test 5: TEST OK [0.011 secs, 3508 KB] All tests OK. Your program ('sprime') produced all correct answers! This is your submission #2 for this problem. Congratulations! Here are the test data inputs: ------- test 1 ---- 4 ------- test 2 ---- 5 ------- test 3 ---- 6 ------- test 4 ---- 7 ------- test 5 ---- 8 Keep up the good work! Thanks for your submission!