7-1 Prime Day (20 分)
The above picture is from Sina Weibo, showing May 23rd, 2019 as a very cool "Prime Day". That is, not only that the corresponding number of the date 20190523
is a prime, but all its sub-strings ended at the last digit 3
are prime numbers.
Now your job is to tell if a given date is a Prime Day.
Input Specification:
Each input file contains one test case. For each case, a date between January 1st, 0001 and December 31st, 9999 is given, in the format yyyymmdd
.
Output Specification:
For each given date, output in the decreasing order of the length of the substrings, each occupies a line. In each line, print the string first, followed by a space, then Yes
if it is a prime number, or No
if not. If this date is a Prime Day, print in the last line All Prime!
.
Sample Input 1:
20190523
Sample Output 1:
20190523 Yes
0190523 Yes
190523 Yes
90523 Yes
0523 Yes
523 Yes
23 Yes
3 Yes
All Prime!
Sample Input 2:
20191231
Sample Output 2:
20191231 Yes
0191231 Yes
191231 Yes
91231 No
1231 Yes
231 No
31 Yes
1 No
题目大意:
给出一个日期,判断这个日期每去掉第一位后的数字是否为素数。
思路:
1.存储日期用整型;
2.去掉第一位,while取余,同时除数也自除10。
代码:
// 2021.03.03 16:15-17:15
#include <iostream>
#include <math.h>
#include <string>
#include <algorithm>
using namespace std;
// 判断素数
bool isPrime(int n) {
if (n <= 1)
return false;
int sqr = (int)sqrt(1.0 * n);
for (int i = 2; i <= sqr; i++) {
if (n % i == 0)
return false;
}
return true;
}
int main() {
int n;
scanf("%d", &n);
char str[10]; // 用于把当前的数字转换成字符数组,取它的长度,看是否少了“0”
bool flag = true; // 是否全为素数的标志
int q = 10000000; // 去掉第一位数字的除数,不断除10,取每个除第一位的后面的数字
int cnt = 8; // 本来数字该有的数字个数。
while (n != 0) {
sprintf(str, "%d", n); // 把当前数字存入字符数组中,
if (strlen(str) != cnt) // 如果当前数字个数不等于本应该有的数字个数
printf("0"); // 在前面补一个“0”
printf("%d ", n); // 打印当前数字
if (isPrime(n)) // 判断素数
printf("Yes\n");
else {
printf("No\n");
flag = false;
}
n %= q; // 去掉第一个数字
q /= 10; // 除数去个0
cnt--; // 本应该的数字位数-1
}
if (flag) // 如果没有不是素数的,就是全为素数的情况
printf("All Prime!\n");
return 0;
}