题目链接:
题意概括:
判断输入是否为素数,并且翻转180度后也为素数,翻转规则如下:
- 翻转后6与9要互换
- 3、4、7 翻转后无意义,当错误处理(无法组成数,自然就不是素数)
- 其他数翻转后不改变
题解分析:
数据的读入和翻转不是问题,我的处理是直接用数组模拟,其实用 string 做会更好。有一点需要注意的是数据范围是1e16,所以都要用long long。
至于判断素数,其实本题用遍历到平方根的 算法也可以,但是看到大数第一反应还是用了Miller_Rabin算法(米勒拉宾素数判定法,概率素数测试算法,涉及费马小定理等许多数论),这些在之后的博客会详解,不再多提。
AC代码:
#include <stdio.h>
#include <iostream>
using namespace std;
typedef long long ll;
const int T = 9;
ll mod_mult(ll a, ll b, ll mod) { //大数乘法取模
a %= mod;
b %= mod;
ll ans = 0;
while (b) {
if (b & 1) {
ans += a;
if (ans >= mod)
ans -= mod;
}
a <<= 1;
if (a >= mod) a = a - mod;
b >>= 1;
}
return ans;
}
ll mod_pow(ll x, ll n, ll mod) { //快速幂
if (n == 0) return 1;
ll res = mod_pow(mod_mult(x , x , mod), n / 2, mod);
if (n & 1) res = mod_mult(res , x , mod);
return res;
}
bool check(ll a, ll n, ll x, ll t) { //来判断是不是素数
ll ret = mod_pow(a, x, n), last = ret;
for (int i = 1; i <= t; i ++) {
ret = mod_mult(ret, ret, n);
if (ret == 1 && last != 1 && last != n - 1) return true;//合数
last = ret;
}
if (ret != 1) return true;
else return false;
}
bool Miller_Rabin(ll n) //Miller_Rabin算法
{
if( n < 2) return false;
if( n == 2) return true;
if(!(n & 1)) return false;//偶数
ll x = n - 1, t = 0;
while (!(x & 1)) { x >>= 1; t++;}
for (int i = 0; i < T; i ++) {
ll a = rand() % (n - 1) + 1;
if (check(a, n, x, t))
return false;
}
return true;
}
int main(){
int temp[17], cnt=0;
ll n;
bool flag = true;
scanf("%lld",&n);
if(flag = Miller_Rabin(n))
while(n > 0) {
temp[cnt] = n % 10;
n = n / 10;
if (temp[cnt] == 3 || temp[cnt] == 4 || temp[cnt] == 7)
{flag = false; break;}
else if(temp[cnt] == 6)
temp[cnt] = 9;
else if(temp[cnt] == 9)
temp[cnt] = 6;
cnt ++;
}
if(flag){
for(int i = 0; i < cnt ; i ++)
n = n * 10 + temp[i];
if (!Miller_Rabin(n))
flag = false;
}
if (flag)
printf("yes\n");
else printf("no\n");
}
Upside down primes
Last night, I must have dropped my alarm clock. When the alarm went off in the morning, it showed 51:80 instead of 08:15. This made me realize that if you rotate a seven segment display like it is used in digital clocks by 180 degrees, some numbers still are numbers after turning them upside down.


My favourite numbers are primes, of course. Your job is to check whether a number is a prime and still a prime when turned upside down.
Input Format
One line with the integer in question
.
will not have leading zeros.
Output Format
Print one line of output containing "yes" if the number is a prime and still a prime if turned upside down, "no" otherwise.
样例输入1
| 151 |
样例输出1
| yes |
样例输入2
| 23 |
样例输出2
| no |
样例输入3
| 18115211 |
样例输出3
| no |

本文深入探讨了Upsidedown Primes的概念,即数字旋转180度后仍为素数的情况,同时介绍了如何使用Miller-Rabin算法进行高效的大数素性测试。通过具体的代码实现,展示了数据翻转和素性判断的过程。
2384

被折叠的 条评论
为什么被折叠?



