• 找出输入区间内的回文质数


    假设输入区间为[a, b],a>0,则回文质数满足以下条件:
    1.为质数(废话)
    2.必须为回文数(正着看倒着看是一样),但这个回文数的位数必须为奇数位(11除外),为什么呢?
       因为位数为偶数的回文数必然是11的倍数,即它不是质数,具体证明如下:
       对于数字abcd,abcd = 1000*a + 100*b + 10*c + d = (1100*a - 110*a + 11*a - a) + (110*b - 11*b + b) + (11*c - c) + d = (1100*a - 110*a + 11*a) + (110*b - 11*b) + 11*c + (b + d - a - c),从最后的式子可以看出前三项都是11的倍数,最后一项(b + d - a -c)为0,因为根据回文数的性质可知 b == c, a == d,从而证明了abcd不是质数。

    从上面的两个性质,便可写出相应的函数,然后进行判断,在判断的时候,先判断是否为回文数,再判断是否为质数,因为在区间内,回文数往往比质数少。(记得排除11)

     

    #include <iostream>
    using namespace std;

    //whether the value is odd bits and is a palindrome number, except 11
    bool is_oddbits_palindrome_number(int value);
    //whether value is prime
    bool is_prime(int value);
    int main()
    {
    int a;
    int b;
    scanf(
    "%d%d", &a, &b);
    for(int i = a; i <= b; i++)
    {
    //is_oddbits_palindrome_number is revoked first
    if(is_oddbits_palindrome_number(i) && is_prime(i))
    printf(
    "%d\n", i);
    }
    return 0;
    }

    bool is_oddbits_palindrome_number(int value)
    {
    char s[16];
    itoa(value, s,
    10);
    int bits = strlen(s);
    //odd bits
    if(!(bits%2) && value != 11)
    return false;
    //whether is palindrome
    for(int i = 0; i < bits/2; i++)
    {
    if(s[i] != s[bits - 1 - i])
    return false;
    }
    return true;
    }

    bool is_prime(int value)
    {
    int middle = value/2;
    for(int i = 2; i <= middle; i++)
    if(!(value%i))
    return false;
    return true;
    }

  • 相关阅读:
    CCF201604试题
    CCF201512试题
    CCF201509试题
    CCF201509试题
    CCF201503试题
    CCF201503试题
    CCF201412试题
    CCF201412试题
    CCF201409试题
    CCF201409试题
  • 原文地址:https://www.cnblogs.com/null00/p/2065047.html
Copyright © 2020-2023  润新知