PAT_甲级_1152

Solution

  1. universal header file: #include<bits/stdc++.h>.
    ios::sync_with_stdio(false); cin.tie(0);make IO more efficient !
  2. s.substr(i,k)extract a substring from s, starting from index i, and there are k characters.
  3. module: isPrime(int n)
    note: check if n is 0 or 1
  4. more important: when you find a solution, output the string instead of int.

Sample Input 1:

20 5
23654987725541023819

Sample Output 1:

49877

Sample Input 2:

10 3
2468024680

Sample Output 2:

404

Code

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

bool isprime(int t)
{
	// 这里需要单独判断t==0和t==1的情况
	if (t == 0 || t == 1) return  false;
	for (int i = 2; i*i <= t; i++)
	{
		if (t%i == 0)
			return false;
	}
	return true;
}

int main()
{
	int l, k;
	cin >> l >> k;
	string s;
	cin >> s;
	for (int i = 0; i < l - k + 1; i++)
	{
		string t = s.substr(i, k);
		int tmp = stoi(t);
		if (isprime(tmp))
		{
			// 输出字符串即可,输出数字是不行的,即使在数字前面加了'0'
			cout << t << endl;
			system("pause");
			return 0;
		}
	}
	cout << "404" << endl;
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/liyingjiehh/article/details/85213418
今日推荐