Last night, I must have dropped my alarm clock. When the alarm went off in the morning, it showed 51:8051:80instead of 08:1508:15. This made me realize that if you rotate a seven segment display like it is used in digital clocks by 180180 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 NN in question (1 \le N \le 10^{16})(1≤N≤1016). NN 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
解题思路:
判断数字本身及依题意转置后的数字是否均为素数。数字不大,用string进行输入、转置快且方便。复杂度根号n的素数判断应该不会超时。但解题时还是使用了米勒罗宾,旨在巩固有关知识。
AC代码:
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
ll ModMul(ll a,ll b,ll n)//快速积取模 a*b%n
{
ll ans=0;
while(b)
{
if(b&1)
ans=(ans+a)%n;
a=(a+a)%n;
b>>=1;
}
return ans;
}
ll ModExp(ll a,ll b,ll n)//快速幂取模 a^b%n
{
ll ans=1;
while(b)
{
if(b&1)
ans=ModMul(ans,a,n);
a=ModMul(a,a,n);
b>>=1;
}
return ans;
}
bool miller_rabin(ll n) //Miller-Rabin素数检测算法
{
ll i,j,a,x,y,t,u,s=10;
if(n==2)
return true;
if(n<2||!(n&1))
return false;
for(t=0,u=n-1; !(u&1); t++,u>>=1); //n-1=u*2^t
for(i=0; i<s; i++)
{
a=rand()%(n-1)+1;
x=ModExp(a,u,n);
for(j=0; j<t; j++)
{
y=ModMul(x,x,n);
if(y==1&&x!=1&&x!=n-1)
return false;
x=y;
}
if(x!=1)
return false;
}
return true;
}
char number[17],tran[17];
int main()
{
gets(number);
int i, j = 0, length = strlen(number);
for(i = length-1; i>=0 ; i--)
{
if(number[i] == '0')
{
tran[j] = '0';
j++;
}
if(number[i] == '1')
{
tran[j] = '1';
j++;
}
if(number[i] == '2')
{
tran[j] = '2';
j++;
}
if(number[i] == '3')
{
printf("no");
return 0;
}
if(number[i] == '4')
{
printf("no");
return 0;
}
if(number[i] == '5')
{
tran[j] = '5';
j++;
}
if(number[i] == '6')
{
tran[j] = '9';
j++;
}
if(number[i] == '7')
{
printf("no");
return 0;
}
if(number[i] == '8')
{
tran[j] = '8';
j++;
}
if(number[i] == '9')
{
tran[j] = '6';
j++;
}
}
tran[j] = 0;
ll number1=atoll(number);
if( !miller_rabin(number1) )
{
printf("no");
return 0;
}
ll number2=atoll(tran);
if( miller_rabin(number2) )
printf("yes");
else
printf("no");
return 0;
}