pat-1015 Reversible Primes (进制转换,逆序输出,判断素数,细节很重要)

这篇博客内容有待我修改!-8.15 留

题目链接

思路:

进制转换,逆序输出,判断素数,一步步做就可以了,不过要注意细节!刚开始很麻烦的写了一百多行,把一个函数拆成两个函数写,重复的部分很多,删删改改简化了一下。

#include <iostream>
#include <cstring>
#include <iomanip>
#include <cstdio>
#include <cmath>

using namespace std;
bool is_prime(int a){
    int i;
    if(a == 1|| a == 0)//注意特殊情况
        return false;
    
    for(i = 2;i <= sqrt((double)a);i++){
        if(a % i == 0)
            return false;
    }
    
    return true;
}
int turn(int num,int  k){
    int a[100],i,j,res;
    i = 0;
    while(num != 0){
        a[i] = num % k;
        i++;//注意这里的i++不要合并写成a[i++]这样第一个数输入的是a[1]
        num /= k;
    }
    res = 0;
    for(j = i - 1;j >= 0;j--){//同时翻转数字的每一位 && 输出这个数字
        res += a[j] * pow(k,i-j-1);
        //printf("res:   %d\n",res);
    }

    return res;
    
}


int main() {
    int n,d,k;
    while(~scanf("%d",&n) ){
        if(n<0)
            break;
        scanf("%d",&d);
        k=turn(n, d);
        if(is_prime(n) && is_prime(k))//它本身是不是素数也要判断的
            printf("Yes\n");
        else
            printf("No\n");
       
        
        
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hzyhfxt/article/details/81629024
今日推荐