PAT Level B 1094 Google's Recruitment (20 points) Python

In July 2004, Google erected a huge billboard (pictured below) on Silicon Valley's Highway 101 for recruitment. The content is super simple, it is a URL ending in .com, and the previous URL is a 10-digit prime number, which is the first 10-digit continuous number in the natural constant e. Those who can find this prime number can enter the next step of the recruitment process by visiting this Google website.

Google Recruitment

The natural constant e is a well-known transcendental number. The first few digits are written like this: e = 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642 7427466391 932003059921... The 10 digits in bold are the answer.

This question requires you to program to solve a more general problem: from any given number of length L, find the prime number consisting of the earliest K-digit continuous number.

Input format:

Enter 2 positive integers in the first line, which are L (a positive integer not exceeding 1000, which is the length of the number) and K (a positive integer less than 10). The next line gives a positive integer N of length L.

Output format:

Output the prime number composed of the earliest consecutive K digits in N in one line. If such a prime number does not exist, 404 is output. Note that the leading zeros in the original numbers are also counted within the number of digits. For example, if you find a 4-digit prime number in 200236, 0023 is the solution; but the first 2 cannot be output as 0002, because the leading zero of this 2 does not exist in the original number.

Input example 1:

20 5
23654987725541023819

Output sample 1:

49877

Input example 2:

10 3
2468024680

Output sample 2:

404

Problem-solving ideas:

The two main points of this question, one is to cut the input string (number) according to the required length. This is easier to implement with Python, and you can use the slice directly.

The other is to determine whether the number obtained by slicing is a prime number. Judging prime numbers can be found in my other blog: Judging prime numbers (prime numbers) Python

AC code:

import math


def isPrime(n):
    if n <= 3:
        return n >= 2
    else:
        if (n + 1) % 6 != 0 and (n - 1) % 6 != 0:
            return False
        for i in range(2, int(math.sqrt(n)) + 1):
            if n % i == 0:
                return False
    return True


s, n = map(int, input().split())  # 获取两个数字:s是题目要求,不做他用,n是切割长度
m = input()  # 输入的字符串(数字) 
if n <= len(m):  # 如果n>m的长度,就没有判断的必要了,可以直接跳过
    for i in range(len(m) - n + 1):  # 然后一个个遍历判断
        if isPrime(int(m[i:i + n])):  # 找到符合要求的字符串以后,输出然后退出程序
            print(m[i:i + n])
            exit(0)
print('404')

Guess you like

Origin blog.csdn.net/weixin_44289959/article/details/111239959