1152 Google Recruitment

题目大意不难懂,在一串字符中找到第一个K位素数。

20分的题,暴力就能做。有两个小点,一个是字符串string转成数字有一个stoi函数,还有一个就是截取string字符串中某一段连续的子串可以简洁写为string ts(s,i,l),其中s是母串,i是起始位置,j是要截取的长度。

判断素数用O(√)判断即可,详见代码。

#include <iostream>
#include <cstring>
#include <string>
#include <sstream>
#include <string>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <map>
#define maxn
#define INF 0x3f3f3f3f
#define EPS 1e-6
#define pi acos(-1.0)
using namespace std;
typedef long long ll;

bool is_prime(string s)
{
    int tmp=stoi(s);
    if(tmp==1)
        return false;
    if(tmp==2||tmp==3)
        return true;
    for(int i=2;i*i<=tmp;i++)
    {
        if(tmp%i==0)
            return false;
    }
    return true;
}
int main()
{
    string s;
    int l,k;
    cin>>l>>k;
    cin>>s;
    int flag=0;
    for(int i=0;i<l-k+1;i++)
    {
        string ts(s,i,k);
        if(is_prime(ts))
        {
            cout<<ts<<endl;
            flag=1;
            break;
        }
    }
    if(flag==0)
        cout<<"404"<<endl;
    
}
View Code

 

posted on 2019-01-21 18:58  FTA_Macro  阅读(242)  评论(0编辑  收藏  举报

导航