PAT甲级1152 Google Recruitment (20分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

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:

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.

Sample Input 1:

20 5
23654987725541023819

Sample Output 1:

49877

Sample Input 2:

10 3
2468024680

Sample Output 2:

404

二、解题思路

对于这道题,我们可以写两个函数,一个用来把字符串转换成数字,一个用来判断数字是否为素数,接着对于输入的长字符串,我们进行遍历,每一次取一段字符子串,转化成数字,然后判断是否为素数,如果找到了,就直接输出然后return,如果没有找到,在最后输出404即可。

三、AC代码

#include<iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
LL toNum(string tmp)    //将字符串转化成数字的函数
{
    
    
    int sze = tmp.size();
    LL ans = 0;
    for(int i=0; i<sze; i++)
    {
    
    
        ans = ans*10 + tmp[i] - '0';
    }
    return ans;
}
bool checkprime(LL num) //判断素数
{
    
    
    for(int i=2; i*i <= num; i++)
    {
    
    
        if(num %i == 0) return false;
    }
    return true;
}
int main()
{
    
    
    int n, K;
    string str;
    scanf("%d%d", &n, &K);
    cin >> str;
    for(int i=0; i+K <= n; i++)
    {
    
    
        string tmp = str.substr(i, K);  //子字符串
        LL num = toNum(tmp);
        if(checkprime(num))
        {
    
    
            cout << tmp << endl;
            return 0;
        }
    }
    printf("404\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/109126326