以上图片来自新浪微博,展示了一个非常酷的“全素日”:2019年5月23日。即不仅20190523
本身是个素数,它的任何以末尾数字3
结尾的子串都是素数。
本题就请你写个程序判断一个给定日期是否是“全素日”。
输入格式:
输入按照 yyyymmdd
的格式给出一个日期。题目保证日期在0001年1月1日到9999年12月31日之间。
输出格式:
从原始日期开始,按照子串长度递减的顺序,每行首先输出一个子串和一个空格,然后输出 Yes
,如果该子串对应的数字是一个素数,否则输出 No
。如果这个日期是一个全素日,则在最后一行输出 All Prime!
。
输入样例 1:
20190523
输出样例 1:
20190523 Yes
0190523 Yes
190523 Yes
90523 Yes
0523 Yes
523 Yes
23 Yes
3 Yes
All Prime!
输入样例 2:
20191231
输出样例 2:
20191231 Yes
0191231 Yes
191231 Yes
91231 No
1231 Yes
231 No
31 Yes
1 No
分析:使用num储存合数的个数,如果最后num为0,则表示要输出”All Prime!”。使用string s存储输入的数字。可以使用while循环,每次查询当前数值是不是素数,然后使用erase()函数删除第一个数字,如此循环到s长度为0。可以直接使用函数stoi(),将string转化成int类型。每次我们判断当前的数是不是素数,并直接输出。
#include <iostream>
#include <cmath>
using namespace std;
int num;
string s;
int is_prime(int x) {
if (x < 2) return 0;
for (int i = 2; i <= sqrt(x); i++)
if (x % i == 0) return 0;
return 1;
}
int main(){
cin >> s;
num = s.size();
while (s.size()) {
cout << s << ' ' << (is_prime(stoi(s)) ? "Yes" : "No") << '\n';
if (is_prime(stoi(s))) --num;
s.erase(s.begin());
}
if (num == 0) cout << "All Prime!";
return 0;
}