PAT甲级1152Google Recruitment

题目链接

https://pintia.cn/problem-sets/994805342720868352/problems/1071785055080476672

题解

涉及到的英语知识

  • recruitment

    招聘

  • the first 10-digit prime found in consecutive digits of the natural constant e

    由自然常数e的连续数字中的第一个10位素数

  • prime

    素数

  • consecutive

    连续的,连贯的

  • transcendental number

    超越数:在数论中,超越数是指任何一个不是代数数的无理数。只要它不是任何一个有理系数代数方程的根,它即是超越数。最著名的超越数是e以及π。

思路、代码以及注意点

  • 题目要求
    • 题目给出L位的数字N,要求求出其中第一个K位的素数,如果不存在则输出404
    • 提示:开头的0也算是素数的一部分,比如0002应和2等价
  • 思路
    • 遍历字符串并取子串,判断它是否为素数,找到第一个素数即可,找不到的话就输出404
  • 注意点
    • 如果找到了第一个素数,则输出结果时要输出字符串,方便处理0002这种情况
    • 找不到第一个素数,以字符串或者数字形式输出404都可以
// Problem: PAT Advanced 1152
// URL: https://pintia.cn/problem-sets/994805342720868352/problems/1071785055080476672
// Tags: String Prime

#include <iostream>
#include <string>
using namespace std;

bool isPrime(int num);

int main()
{
    // 题目给出L位的数字N,要求求出其中第一个K位的素数,如果不存在则输出404
    // 提示:开头的0也算是素数的一部分,比如0002应和2等价
    int L, K;  // 数字位数,所求素数位数
    string N;  // 数字
    cin >> L >> K >> N;
    for (int i = 0; i <= L - K; i++){
        string str = N.substr(i, K);
        if (isPrime(stoi(str))){
            cout << str << endl;
            return 0;
        }
    }
    cout << 404 << endl;
    return 0;
}

bool isPrime(int num){
    if (num<=1)
        return false;
    for (int i = 2; i * i <= num; i++)
        if (num % i == 0)
            return false;
    return true;
}

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!


posted @ 2020-08-04 20:10  臭咸鱼  阅读(133)  评论(0编辑  收藏  举报