1015. Reversible Primes (20)

Q: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

A:素数:指在一个大于1的自然数中,除了1和此整数自身外,不能被其他自然数整除的数。

比1大但不是素数的数称为合数。

1和0既非素数也非合数。---注意,0和1既不是素数也不是合数。素数和合数>1

#include<stdio.h>

int isPrime(int n)
{
    int i;
    if(n==0||n==1)         //注意0和1是特殊情况,既不是素数也不是合数!!!!!!原先遗漏了1的情况。
        return 0;
    if(n%2==0)
        return (n==2);
    if(n%3==0)
        return (n==3);
    if(n%5==0)
        return (n==5);
    for(i=7;i*i<=n;i+=2)
    {
        if(n%i==0)
            return 0;
    }
    return 1;
}

int reverse_n(int n,int d)
{
    int sum = 0;
   do
    {
        sum = sum*d + n%d;
        n /= d;
    }while(n != 0);
    return sum;
}

int main()
{
    int d,n;
    while(scanf("%d",&n)!=EOF)
    {
        if(n<0)
            break;
       scanf("%d",&d);
        if(isPrime(n)&&isPrime(reverse_n(n,d)))
            printf("Yes\n");
        else
            printf("No\n");
    }

    return 0;
}

  

posted @ 2013-07-09 10:26  summer_zhou  阅读(325)  评论(0)    收藏  举报