hoj 1004 Prime Palindromes 回文素数

/*

晕,弄少了九位数的那段

据说偶数位的话,除了11是回文素数以外,其他均可被11整除并且是合数,

然后就枚举1位3位5位7位9位数的数,然后判断是否为素数即可

*/

#include <iostream>

#include <cmath>

using namespace std;

long long a,b;

bool judge(long long x)

{

   for(int i=2;i<=(int)sqrt(x*1.0);i++)

      if(x%i==0)

         return false;

   return true;

}

void solve()

{

   long long ans;

   if(a<10)    //1位素数和11

   {

      for(int i=a;i<10;i++)

      {

         if(i>b)

            return;

         if(judge(i))

            cout<<i<<endl;

      }

      cout<<11<<endl;

   }

   if(b>100)       //3位数时

      for(int i=1;i<=9;i+=2)

         for(int j=0;j<=9;j++)

         {

            ans = i*101+j*10;

            if(ans>=a&&ans<=b&&judge(ans))

                cout<<ans<<endl;

            if(ans>=b)

                return;

         }

 

   if(b>10000)        //5位数时

      for(int i=1;i<=9;i+=2)

         for(int j=0;j<=9;j++)

            for(int k=0;k<=9;k++)

            {

                ans = i*10001+j*1010+k*100;

                if(ans>=a&&ans<=b&&judge(ans))

                   cout<<ans<<endl;

                if(ans>=b)

                   return;

            }

 

   if(b>1000000)         //7位数时

   {

      for(int i=1;i<=9;i+=2)

         for(int j=0;j<=9;j++)

            for(int k=0;k<=9;k++)

                for(int m=0;m<=9;m++)

                {

                   ans = i*1000001+j*100010+k*10100+m*1000;

                   if(ans>=a&&ans<=b&&judge(ans))

                      cout<<ans<<endl;

                   if(ans>=b)

                      return;

                }

   }

   if(b>100000000)       //9位数时

   {

      for(int i=1;i<=9;i+=2)

         for(int j=0;j<=9;j++)

            for(int k=0;k<=9;k++)

                for(int m=0;m<=9;m++)

                   for(int r=0;r<=9;r++)

                   {

                      ans = i*100000001+j*10000010+k*1000100+m*101000+r*10000;

                      if(ans>=a&&ans<=b&&judge(ans))

                         cout<<ans<<endl;

                      if(ans>=b)

                         return;

                   }

   }

}

int main()

{

   freopen("sum.in","r",stdin);

   freopen("sum.out","w",stdout);

   while(cin>>a>>b)

   {

      if(a>b)

         swap(a,b);

      solve();

   }

   return 0;

}

原文地址:https://www.cnblogs.com/yejinru/p/2412206.html