这题直接来枚举再判断显然是效率很低的...我是采取构造的方法...首先将2,3,5,7入队列..然后每次从队头取出一个数..枚举再他后面加1~9后还是不是质数..是的话入队...
当然从队头每次取出一个数后...判断下其位数~~若是等于要求的长度就直接输出了..并且因为构造的时候就保证了其顺序...所以输出顺序也会是满足要求的...
Program:
/* ID: zzyzzy12 LANG: C++ TASK: sprime */ #include<iostream> #include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> #include<queue> using namespace std; int getlen(int a) { int k=1,i=0; while (k<=a) { k*=10; i++; } return i; } bool IsPrime(int a) { int k; for (k=2;k<=a/k;k++) if (a%k==0) return false; return true; } int h,p,i,n; queue<int> myqueue; int main() { freopen("sprime.in","r",stdin); freopen("sprime.out","w",stdout); scanf("%d",&n); while (!myqueue.empty()) myqueue.pop(); myqueue.push(2); myqueue.push(3); myqueue.push(5); myqueue.push(7); while (!myqueue.empty()) { h=myqueue.front(); myqueue.pop(); p=getlen(h); if (p==n) { printf("%d\n",h); continue; } for (i=1;i<=9;i+=2) if (IsPrime(h*10+i)) myqueue.push(h*10+i); } return 0; }