第一题
# include<iostream>
# include<string>
# include<iomanip>
# include<cmath>
using namespace std;
bool is_prime(int n){
for(int i = 2; i <= n/2; i++)
{
if(n % i == 0)
return false;
}
return true;
}
int str2num(string s){
int sum = 0, len = s.size();
for(int j = len - 1; j >= 0; j--)
sum += int(s.at(j) - '0') * pow(10, len - 1 - j);
return sum;
}
bool judge(string s){
int len = s.size();
int n;
string s1, s2;
if(len % 2 == 1){
n = len / 2 + 1;
s1 = s.substr(0, n); s2 = s.substr(n - 1, n);
}
else{
n = len / 2;
s1 = s.substr(0, n); s2 = s.substr(n, n);
}
// 在s1和s2都是质数的情况下判断是否是对称的,如果对称则返回true,其他都返回false
if( is_prime(str2num(s1)) && is_prime(str2num(s2)) ){
for(int i = 0; i < n; i++){
if(s1.at(i) != s2.at(n - i - 1))
return false;
}
return true;
}
else
return false;
}
int main(){
int count = 0, n = 0, num = 10;
// 一开始便可以设置右对齐
cout << setiosflags(ios::right);
while(count < 50){
string s = to_string(num++);
if(judge(s)){
// 先留空,再输出,可以得到整齐的输出格式
cout << setw(8) << s;
count ++;
n++;
}
if(n == 5){
n = 0;
cout << endl;
}
}
return 0;
}
代码运行结果如下:
11 22 33 55 77
111 131 171 313 373
717 737 797 979 1111
1331 1771 3113 3773 7117
7337 7997 9779 10101 10701
11311 13131 14941 15151 15751
16761 17971 18181 19191 19991
31113 31313 33733 34743 35353
35953 37373 38383 38983 70107
70907 72727 73337 73937 74347
第二题
# include<ctime>
# include<iostream>
# include<iomanip>
using namespace std;
bool is_leap(int n){
if((n%4 == 0 && n/100 !=0) || n % 400 ==0)
return true;
else
return false;
}
int main(){
int year, month, day, hour, minute, second;
int second_num = time(0);
// 分别计算当前距离1970年1月1日有多少天,以及当前这一天有多少秒
int day_num = second_num /(24 * 60 *60);
second_num = second_num % (24 *60 *60);
// 计算当天时间
hour = second_num / (60 * 60);
second_num = second_num % (60 * 60);
minute = second_num / 60;
second = second_num % 60;
// 计算当前日期
// 从1970年开始,先算年份
// 若今年是平年且剩余天数大于365 或者 今年是闰年剩余天数大于366 则进入循环
// 给年数加一,同时剩余天数减去相应的天数
year = 1970;
while( (is_leap(year) && day_num > 366) || (!is_leap(year) && day_num > 365) ){
if(is_leap(year))
day_num -= 366;
else
day_num -= 365;
year ++;
}
// 根据今年的年份,给month_num数组相应的赋值
int month_l[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int month_c[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int month_num[12];
if(is_leap(year))
for(int i = 0; i < 12; i++)
month_num[i] = month_l[i];
else
for(int i = 0; i < 12; i++)
month_num[i] = month_c[i];
// 计算月份
int i;
for(i = 0; month_num[i] < day_num; i++)
day_num -= month_num[i];
month = i + 1;
// 注意当前日期是已经过去的天数 + 1
day = day_num + 1;
cout << "Current Time(GMT):";
cout << year << "-" << setw(2) << setfill('0') << month << "-" << setw(2) << setfill('0') << day << "," ;
cout << setw(2) << setfill('0') << hour << ":" << setw(2) << setfill('0') << minute << ":" << setw(2) << setfill('0') << second << endl;
return 0;
}
运行结果如下:
Current Time(GMT):2022-11-30,07:34:10