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;
}
全部评论

相关推荐

这算盘打的
程序员小白条:都这样的,都是潜规则,你自己说可以实习一年就行了,实习可以随便跑路的
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 12:05
点赞 评论 收藏
分享
06-15 20:57
已编辑
门头沟学院 Java
CARLJOSEPH...:年轻人有傲气很正常,但是建议工作前洗净傲气。 说实在的,什么奖学金什么奖项的都很一般。尊重你的老师,在有时间的时候去上课,真遇到走不开的事,请态度端正地向你的老师说明情况,请求请假。我相信任何一个有师德的老师都会允许的(我的老师就是这样)。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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