• 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
  • 相关阅读:
    面向对象高级
    Intellij IDEA 激活码 | Intellij IDEA 注册码
    如何保证核心链路稳定性的流控和熔断机制?
    消息模型:主题和队列有什么区别?
    MySQL中悲观锁和乐观锁到底是什么?
    SQL是如何在数据库中执行的?
    ZooKeeper 面试题(30道ATM精选问题)
    线上服务的FGC问题排查,看这篇就够了!
    一次线上JVM调优实践,FullGC40次/天到10天一次的优化过程
    由多线程内存溢出产生的实战分析
  • 原文地址:https://www.cnblogs.com/chenyg32/p/3277613.html
Copyright © 2020-2023  润新知