博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PAT 1015
阅读量:5796 次
发布时间:2019-06-18

本文共 1809 字,大约阅读时间需要 6 分钟。

1015. Reversible Primes (20)

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

采用素数筛选法,若$i$为素数,则$i*j$不是素数,其中$j=2,3,....$。这样可以不用判断哪个数为素数,因为非素数的都必定会被筛选出来。

 

代码

#include <stdio.h>
#include <math.h>
char primerTable[500000];
void calculatePrimerTable();
int num2array(int,int,int*);
int array2num(int*,int,int);
int main()
{
    calculatePrimerTable();
    int N,D,len;
    int data[32];
    while(scanf("%d",&N)){
        if(N < 0)
            break;
        scanf("%d",&D);
        if(primerTable[N] == 'N'){
            printf("No\n");
            continue;
        }
        len = num2array(N,D,data);
        if(primerTable[array2num(data,len,D)] == 'Y')
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}
void calculatePrimerTable()
{
    int i;
    for(i=2;i<500000;i++){
        if(primerTable[i] != 'N'){
            primerTable[i] = 'Y';
            int j,n;
            for(j=2,n=2*i;n<500000;++j,n=j*i){
                primerTable[n] = 'N';
            }          
        }
    }
}
int num2array(int n,int base,int *s)
{
    if(n < 0)
        return 0;
    else if(n == 0){
        s[0] = 0;
        return 1;
    }
    int len = 0;
    while(n){
        s[len++] = n % base;
        n = n / base;
    }
    return len;
}
int array2num(int *s,int len,int base)
{
    int i,n = 0;
    for(i=0;i<len;++i){
        n = n * base + s[i];
    }
    return n;
}

 

posted on
2014-02-20 22:15 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/boostable/p/pat_1015.html

你可能感兴趣的文章
闪回恢复区大小不够。报ORA-19809、ORA-19804
查看>>
C#类的构造
查看>>
部署 & virtualen
查看>>
POJ NOI0105-43 质因数分解
查看>>
数据结构——串的朴素模式和KMP匹配算法
查看>>
jQuery的height()和JavaScript的height总结,js获取屏幕高度
查看>>
FreeMarker-Built-ins for strings
查看>>
验证DataGridView控件的数据输入
查看>>
POJ1033
查看>>
argparse - 命令行选项与参数解析(转)
查看>>
一维数组
查看>>
Linux学习笔记之三
查看>>
2463: [中山市选2009]谁能赢呢?
查看>>
3631: [JLOI2014]松鼠的新家
查看>>
微信公众号
查看>>
Android_内部文件读取
查看>>
QTP的那些事---webtable的一些重要使用集合精解
查看>>
POJ1061 青蛙的约会(扩展欧几里得)题解
查看>>
[JavaWeb]关于DBUtils中QueryRunner的一些解读(转)
查看>>
C/C++之循环结构
查看>>