查看原题
思路:
判断回文+判断质数
初步代码:
#include <bits/stdc++.h>
using namespace std;
bool prime(int n) {
for(int i = 2;i<sqrt(n);++i) {
if(n%i==0) {
return 0;
}
}
return 1;
}
bool huiwen(long long n) {
string a = " ";
string b = " ";
stringstream ss;
ss<<n;
ss>>a;
int k = 0;
for(int i = a.length()-1;i>=0;--i) {
//cout<<a[i]<<"#";
b[k] = a[i];
k+=1;
}
b[k+2] = ' ';
for(int i = 0;i<=a.length();++i) {
// cout<<a[i]<<" "<<b[i]<<endl;
if(a[i]!=b[i]) {
//cout<<a[i]<<" "<<b[i];
return false;
}
}
return true;
}
int main() {
const int m = 11;
long long n;
cin>>n;
int ans = 0;
for(int i = m;i<=n;++i) {
if(prime(i)&&huiwen(i)) {
ans++;
}
}
cout<<ans<<endl;
}
分数:
$color{red} ext{未通过 color{black}{80分}}$
$color{blue} ext{原因: color{red}{答案错误}}$
经确认,由于"bool prime(long long n) {
"中
for(int i = 2;i<sqrt(n);++i) {
if(n%i==0) {
return 0;
}
}
return 1;
部分的i<sqrt(n)
忽略了sqrt(n)
是质数的情况,比如,sqrt(25)
等于5,所以25不是质数,上面忽略了此情况。
修改如下:
$color{blue} ext{修改后分数: color{green}{100}}$
$color{blue} ext{结果: color{green}{正确通过}}$
修改代码:
#include <bits/stdc++.h>
using namespace std;
bool prime(long long n) {
for(int i = 2;i<=sqrt(n);++i) {
if(n%i==0) {
return 0;
}
}
return 1;
}
bool huiwen(long long n) {
string a = " ";
string b = " ";
stringstream ss;
ss<<n;
ss>>a;
int k = 0;
for(int i = a.length()-1;i>=0;--i) {
b[k] = a[i];
k+=1;
}
b[k+1] = ' ';
for(int i = 0;i<=a.length();++i) {
if(a[i]!=b[i]) {
return false;
}
}
return true;
}
int main() {
const int m = 11;
long long n;
cin>>n;
long long ans = 0;
for(int i = m;i<=n;++i) {
if(prime(i)&&huiwen(i)) {
ans++;
}
}
cout<<ans<<endl;
}