PAT---1152 Google Recruitment

题意:要求输出一个数字串中的长度为k的素数串。

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

string list = "024568";
bool isPrime(int x)
{
    int bound = sqrt(double(x))+1;
    for(int i = 2; i <= bound; i++)
        if(x % i == 0)
            return false;
    return true;
}

int main()
{
    int l, k;
    while(cin >> l >> k)
    {
        string str;
        cin >> str;
        string tmp;
        bool flag = false;
        for(int i = 0; i < str.size(); i++)
        {
            tmp = str.substr(i, k);
            //长度小于k
            if(tmp.size() < k)
                break;
                
            int x = stoi(tmp);
            //x是2或者5
            if(x == 2 || x == 5)
            {
                flag = true;
                break;
            }
             //末尾不是以024568结尾
            if(list.find(tmp[k-1]) == -1 && isPrime(x))
            {
                flag = true;
                break;
            }
        }
        if(flag)
            cout << tmp << endl;
        else
            cout << "404" << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/mch2869253130/article/details/88062906