zoukankan      html  css  js  c++  java
  • 4190. Prime Palindromes 一亿以内的质数回文数

    Description

    The number 151 is a prime palindrome because it is both a prime number and a palindrome (it is the same number when read forward as backward). Write a program that finds all prime palindromes in the range of two supplied numbers a and b (5 <= a < b <= 100,000,000); both a and b are considered to be within the range .

    Input

    There are multiple test cases.

    Each case contains two integers, a and b.

    a=b=0 indicates the end of input.

    Output

    For each test case, output the list of palindromic primes in numerical order, one per line.

    Sample Input
     Copy sample input to clipboard
    5 500
    0 0
    
    Sample Output
    5
    7
    11
    101
    131
    151
    181
    191
    313
    353
    373
    383



    题目链接:4190. Prime Palindromes
    题意分析:求给定区间内的质数回文数
    题目分析:
    1.多组测试数据,所以先打表。
    2.先求质数再判断回文,效率低下;所以先构造回文数,再判断质数。
    3.偶数位的回文数都能被11整除,自己证明去。所以,偶数位的回文数除了11都是合数。
    4.一个k位数,可以构造出一个奇数位的回文数。比如13,可以构造131;189可以构造18981.所以100000000内的只要从1构造到9999即可。
    5.若范围为1000000000,那么明显超出int范围,要用long long。当然此题无此陷阱。
    
    
    //http://soj.me/show_problem.php?pid=4190
    #include <iostream>
    #include <cstdio>
    #include <vector>
    #include <cmath>
    #include <algorithm>
    using namespace std;
    
    vector<int> v;
    
    bool prime(int x)
    {
        for (int i = 2; i < sqrt(x+0.5); i++)
            if (x%i == 0)
                return 0;
            
        return 1;
    }
    
    void get()
    {
        // 11是唯一的偶数位的质数回文数。
        v.push_back(11);
        
        //构造奇数位的回文数
        for (int i = 2; i <= 10000; ++i)
        {
            int tmp = i/10, sum;
            
            for (sum = i; tmp != 0; tmp /= 10)
            {
                sum = sum*10 + tmp%10;
            }
            
            if (prime(sum))
                v.push_back(sum);
        }
    }
    int main()
    {
        get();
        sort(v.begin(), v.end());    //因为是不按顺序push,所以要sort
        int a, b;
        while(cin >> a >> b, a||b)
        {
            for (int i = 0; i < v.size(); ++i)
            {
                if (v[i] >= a)
                {
                    if (v[i] > b)
                        break;
                    
                    printf("%d
    ", v[i]);
                }
            }
        }
    }
    View Code
  • 相关阅读:
    把一个数组 赋值给一个新数组
    上传图片时进行压缩
    input上传文件 显示进度条
    vue 后台接口返回文件流地址的下载
    时间戳转换
    JS 两个含有部分相同属性的对象如何快速给对应的key赋值
    javascript中把一个数组的内容全部赋值给另外一个数组
    微信小程序wxs如何使用
    优化内存
    解决position:fiexd相对父元素定位
  • 原文地址:https://www.cnblogs.com/chenyg32/p/3277613.html
Copyright © 2011-2022 走看看