PAT-A 1015. Reversible Primes

1015. Reversible Primes

A reversible prime in any number system is a prime whose “reverse” in that number system is also a prime. For example in the decimal system 73 is a reversible prime because its reverse 37 is also a prime.

Now given any two positive integers N (< 105) and D (1 < D <= 10), you are supposed to tell if N is a reversible prime with radix D.

Input Specification:

The input file consists of several test cases. Each case occupies a line which contains two integers N and D. The input is finished by a negative N.

Output Specification:

For each test case, print in one line “Yes” if N is a reversible prime with radix D, or “No” if not.

Sample Input:

73 10
23 2
23 10
-2

Sample Output:

Yes
Yes
No

程序代码:

#include<stdio.h>
#include<math.h>
#include<string.h>
int convert(int n,int d);
int isPrime(int n);
int main()
{
    int N,D;
    int ans;
    while(1)
    {
        scanf("%d",&N);
        if(N<0)
            break;
        scanf("%d",&D);
        ans= convert(N,D);
        if(isPrime(N)&&isPrime(ans))
        {
            printf("Yes\n");
        }
        else
            printf("No\n");
    }
}
int convert(int n,int d)
{
    char ans[100]={0};
    int  i=0;
    while(n)
    {
        ans[i++]=n%d+'0';
        //此处必须保存字符,不能直接保存数字,因为0与字符串结束符'\0'的值一样
        n=n/d;
    }
    ans[i]='\0';
    int sum = 0;
    int len = strlen(ans);
    for(i=0;i<len;i++)
    {
        sum = sum*d+(ans[i]-'0');
    }
    return sum;
}
int isPrime(int n)   
{
    if(n<2)
        return 0;
    int i=2;
    for(i=2;i<=sqrt(n);i++){
        if((n%i)==0)
            return 0;
    }
    return 1;
}
全部评论

相关推荐

11-11 17:45
门头沟学院 Java
扶老蟑螂过马路被无证...:1. 技术栈那里把数据结构删了,小中厂用不上,大厂手撕能难死你,linux那里可以考虑删掉,还不如换个git团队协作开发 2.不要使用一些项目不匹配的技术,例如分库分表和你上边的ddd,真正使用ddd的都是【超】大规模,大部分都仍然使用多模块聚合mvc,这样虽然看起来高大上,但是新增了前期协定需求跟后期维护的成本,因为开发中都是选择最适合当起版本的开发方式跟中间件,这样反而会体现你为了学而学(因为可能面试官都不完全熟悉ddd,然后问你你也回答不出深度) 3.项目写了很多的redis使用,为什么技术栈不写上redis 4.项目技术栈跟业务需求高度重合,完全可以整合成一个,然后再去弄一个感兴趣的其他业务或者轮子,或者把上面的一个换下包装 5.奖项自己编一点奖学金,加个四六级,删掉蓝桥杯
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务