洛谷 P1217.[USACO1.5]回文质数 Prime Palindromes

本文详细解析洛谷P1217题目,介绍如何寻找特定范围内的回文质数,包括算法实现和代码示例。

洛谷 P1217.[USACO1.5]回文质数 Prime Palindromes

题目描述

因为 151 既是一个质数又是一个回文数(从左到右和从右到左是看一样的),所以 151 是回文质数。

写一个程序来找出范围 [ a,b ] (5≤a<b≤100,000,000)( 一亿)间的所有回文质数。

输入格式

第 1 行: 二个整数 a 和 b .

输出格式

输出一个回文质数的列表,一行一个。

输入输出样例
输入样例#1
5 500
输出样例#1
5
7
11
101
131
151
181
191
313
353
373
383
说明/提示

Hint 1: Generate the palindromes and see if they are prime.

提示 1: 找出所有的回文数再判断它们是不是质数(素数).

Hint 2: Generate palindromes by combining digits properly. You might need more than one of the loops like below.

提示 2: 要产生正确的回文数,你可能需要几个像下面这样的循环。

题目翻译来自NOCOW。

USACO Training Section 1.5

产生长度为5的回文数:

for (d1 = 1; d1 <= 9; d1+=2) {    // 只有奇数才会是素数
     for (d2 = 0; d2 <= 9; d2++) {
         for (d3 = 0; d3 <= 9; d3++) {
           palindrome = 10000*d1 + 1000*d2 +100*d3 + 10*d2 + d1;//(处理回文数...)
         }
     }
 }
题目思路
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll j=0;
bool hw(ll num)     // 回文数函数
{
    ll t = 0, n = num,w = 0;    //  w 位数,偶数位回文数除11外都不为质数
    while (n)
    {
        t *= 10;
        t += n % 10;
        n /= 10;
        w++;
    }
    if(num>11&&w%2==0){
        j = pow(10,w) - 1;
        return false;
    }
    return t == num;
}

bool zs(ll n)     // 质数函数
{
    for (ll i = 3; i * i <= n; i+=2)
    {
        if (!(n % i))return false;
    }
    return true;
}

int main()
{
    ll a, b;
    scanf("%lld%lld", &a, &b);
    if (!(a % 2))a += 1;        // 偶数不为质数
    for (j = a; j <= b; j += 2)
    {
        if (hw(j) && zs(j))
            printf("%lld\n", j);
    }
    return 0;
}
### USACO P1217 Prime Palindromes 的 Java 实现 以下是基于枚举方法并结合回文数构造的方式实现的一个高效解决方案。此方案利用了回文数的特性以及质数判断算法,从而避免了大量的冗余计算。 #### 方法概述 为了提高效率,可以先生成给定范围内所有的回文数,再逐一验证这些回文数是否为质数。这种方法显著减少了需要测试的数量,因为大多数非回文数可以直接排除[^4]。 #### AC代码 (Java) ```java import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int b = scanner.nextInt(); List<Integer> result = findPalindromePrimes(a, b); for (int num : result) { System.out.println(num); } } private static boolean isPrime(int n) { if (n < 2) return false; if (n == 2 || n == 3) return true; // 特殊情况处理 if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i += 6) { // 跳过偶数和能被3整除的数 if (n % i == 0 || n % (i + 2) == 0) return false; } return true; } private static List<Integer> generatePalindromes(int length) { List<Integer> palindromes = new ArrayList<>(); if (length == 1) { for (int i = 0; i <= 9; i++) { palindromes.add(i); } return palindromes; } int halfLength = (length + 1) / 2; int start = (int) Math.pow(10, halfLength - 1); int end = (int) Math.pow(10, halfLength); for (int prefix = start; prefix < end; prefix++) { String s = Integer.toString(prefix); StringBuilder sb = new StringBuilder(s); if (length % 2 == 0) { sb.append(new StringBuilder(s).reverse()); } else { sb.append(new StringBuilder(s.substring(0, s.length() - 1)).reverse()); } palindromes.add(Integer.parseInt(sb.toString())); } return palindromes; } private static List<Integer> findPalindromePrimes(int a, int b) { List<Integer> primes = new ArrayList<>(); for (int len = 1; len <= 8 && Math.pow(10, len - 1) <= b; len++) { List<Integer> candidates = generatePalindromes(len); // 构造长度为len的所有回文数 for (int candidate : candidates) { if (candidate >= a && candidate <= b && isPrime(candidate)) { primes.add(candidate); } } } return primes; } } ``` --- #### 关键点解释 1. **回文数生成逻辑**: 使用 `generatePalindromes` 函数动态生成指定长度的回文数。对于奇数长度的回文数,中字符不重复;而对于偶数长度,则完全对称。 2. **质数检测优化**: 利用了跳过偶数和能被3整除的数的方法,并进一步缩小循环范围至平方根级别 \( \sqrt{n} \)。 3. **边界条件处理**: 需要特别注意上下界 `[a, b]` 和最大可能值 \(10^8\) 的约束条件[^2]。 --- #### 时复杂度分析 由于只针对回文数进行质数检验,而且回文数数量远少于总自然数数量,因此该算法的时复杂度相较于暴力解法大幅降低。具体时复杂度取决于区大小和回文数分布密度。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wynpz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值