The picture above is from Sina Weibo, showing a very cool "Vegan Day": May 23, 2019. That is, not only 20190523
is it a prime number itself, but any 3
substring of it that ends with a number at the end is also a prime number.
In this question, you are asked to write a program to determine whether a given date is a "full vegetarian day".
Input format:
The input yyyymmdd
is given a date in the format of . The guaranteed date of the topic is between January 1, 0001 and December 31, 9999.
Output format:
Starting from the original date, in descending order of substring length, each line first outputs a substring and a space, and then outputs Yes
, if the number corresponding to the substring is a prime number, otherwise output No
. If the date is a vegan day, it is output on the last line All Prime!
.
Input sample 1:
20190523
Output sample 1:
20190523 Yes
0190523 Yes
190523 Yes
90523 Yes
0523 Yes
523 Yes
23 Yes
3 Yes
All Prime!
Input sample 2:
20191231
Output sample 2:
20191231 Yes
0191231 Yes
191231 Yes
91231 No
1231 Yes
231 No
31 Yes
1 No
Problem-solving ideas:
Take out the corresponding string to judge whether it is a prime number
Code example:
#include <bits/stdc++.h>
using namespace std;
//素数判断
bool isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
int main() {
string date;
cin >> date;
bool flag = true;
for (int i = 0; i < date.length(); i++) {
//从date的第i号位置开始往后取所有的字符给date_son
string date_son = date.substr(i);
int num = stoi(date_son);
if (isPrime(num)) {
cout << date_son << " " << "Yes\n";
}
else {
cout << date_son << " " << "No\n";
flag = false;
}
}
if (flag) {
cout << "All Prime!\n";
}
return 0;
}
operation result: