PAT A1152 Google Recruitment [素数+字符串处理]

题目描述

链接
给定长度为L的字符串,求第一个长度为k的子串,使之为素数

分析

  • 问题分解为:遍历,求子串,判断素数
  • 注意边界:长度不足的话就舍弃掉

代码

#include<bits/stdc++.h>
using namespace std;

bool isprime(string s){
    int d = stoi(s);
    if(d == 1 || d == 0) return false;
    if(d == 2) return true;
    for(int i=2;i<=(int)sqrt(d);i++){
        if(d % i == 0) return false;
    }
    return true;
}

int main(){
    int n,m;
    string s;
    cin>>n>>m;
    cin>>s;
    int len = s.length();
    bool ans = 0;
    for(int i=0; i<len; i++){
        if(i+m-1 >= len) break;
        string t = s.substr(i, m);
        if(isprime(t)){
            cout<<t<<endl;
            ans = 1;
            break;
        }
    }
    if(!ans) cout<<"404"<<endl;
}

猜你喜欢

转载自www.cnblogs.com/doragd/p/11449028.html