1152 Google Recruitment (20 分)

从任一给定的长度为 L 的数字中,找出最早出现的 K 位连续数字所组成的素数。

Find the first K-digit prime in consecutive digits of any given L-digit number.

输入格式(Input Specification):

输入在第一行给出 2 个正整数,分别是 L(不超过 1000 的正整数,为数字长度)和 K(小于 10 的正整数)。接下来一行给出一个长度为 L 的正整数 N。

Each input file contains one test case. Each case first gives in a line two positive integers: L (≤ 1,000) and K (< 10), which are the numbers of digits of the given number and the prime to be found, respectively. Then the L-digit number N is given in the next line.

输出格式(Output Specification):

在一行中输出 N 中最早出现的 K 位连续数字所组成的素数。如果这样的素数不存在,则输出 404。注意,原始数字中的前导零也计算在位数之内。例如在 200236 中找 4 位素数,0023 算是解;但第一位 2 不能被当成 0002 输出,因为在原始数字中不存在这个 2 的前导零。

For each test case, print in a line the first K-digit prime in consecutive digits of N. If such a number does not exist, output 404 instead. Note: the leading zeroes must also be counted as part of the K digits. For example, to find the 4-digit prime in 200236, 0023 is a solution. However the first digit 2 must not be treated as a solution 0002 since the leading zeroes are not in the original number.

输入样例 1(Sample Input 1):

20 5
23654987725541023819

输出样例 1(Sample Output 1):

49877

输入样例 2(Sample Input 2):

10 3
2468024680

输出样例 2(Sample Output 2):

404

代码:

#include<iostream>
#include<cstring>
using namespace std;
bool isPrime(int n){
    if(n==0||n==1)  return false;
    for(int i=2;i*i<=n;i++)
        if(n%i==0)  return false;
    return true;
}
int main(){
    int l,k;
    string s;
    cin>>l>>k>>s;
    for(int i=0;i<=l-k;i++){
        string str=s.substr(i,k);
        int num=stoi(str);
        if(isPrime(num)){
            cout<<str;
            return 0;
        }
    }
    printf("404");
    return 0;
}

结果:

分析:

  • s.substr(i,k):截取子字符串 从下标i开始截取k个字符.
  • stoi(t):将字符串t转为int型(string to int); to_string(t):将int型变量t转为字符串.
  • 输出时,因为原始数字中的前导零也计算在位数之内,所以输出的应该是字符串.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值