目录
1,题目描述
- recruitment:招募,招聘;
Sample Input 1:
20 5
23654987725541023819
Sample Output 1:
49877
Sample Input 2:
10 3
2468024680
Sample Output 2:
404
题目大意
给出一个字符串,找到字符串中第一个长度为K的质数(K个数连续),若不存在则输出404.
2,思路
每次从字符串s中截取长度为K的子字符串s1,将其转换为int型数字,并判断是否为质数,若是则将其补满K个数字输出(用0来补)。
3,AC代码
#include<bits/stdc++.h>
using namespace std;
int L, K;
bool isPrime(int x){
if(x <= 1) return false;
for(int i = 2; i <= sqrt(x); i++){
if(x % i == 0)
return false;
}
return true;
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
string s, s1;
scanf("%d%d", &L, &K);
cin>>s;
for(int i = 0; i + K - 1 < L; i++){
s1 = s.substr(i, K);// !!!从i开始的K个元素 不是i到K
int num = stoi(s1);
if(isPrime(num)){
s1 = to_string(num);
while(s1.size() < K)
s1 = '0' + s1;
cout<<s1;
return 0;
}
}
printf("404");
return 0;
}
4,解题过程
第一搏
不断截取K个字符串,将其转化为int类型,并判断是否为质数(Prime);
#include<bits/stdc++.h>
using namespace std;
int L, K;
bool isPrime(int x){
if(x <= 1) return false;
for(int i = 2; i <= sqrt(x); i++){
if(x % i == 0)
return false;
}
return true;
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
string s, s1;
scanf("%d%d", &L, &K);
cin>>s;
for(int i = 0; i + K - 1 < L; i++){
s1 = s.substr(i, K);// !!!从i开始的K个元素 不是i到K
int num = stoi(s1);
if(isPrime(num)){
printf("%d", num);
return 0;
}
}
printf("404");
return 0;
}
第二搏
测试点2:注意到print in a line the first K-digit prime in consecutive digits of N,意思就是说如果质数为0023的话,要输出0023而不是23,于是