zoukankan      html  css  js  c++  java
  • P1217 [USACO1.5]回文质数 Prime Palindromes

    题目描述

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

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

    输入格式

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

    输出格式

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

    输入输出样例

    输入 #1
    5 500
    
    输出 #1
    5
    7
    11
    101
    131
    151
    181
    191
    313
    353
    373
    383



    第三天,好吧,又出问题,爆内存了。。。。
    思路:
      从 a到b遍历,先判断是否是回文:用int转string
              在判断是否为质数:string转int
    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();
            String c = "";
            for (int i = a; i <= b; i++) {
                if (i>=10){
                    c = String.valueOf(i);
                    if (reverse(c).equals(c)){
                        int x = Integer.parseInt(c);
                        if (sushu(x)){
                            System.out.println(x);
                        }
                    }
                }else {
                    if (sushu(i)){
                        System.out.println(i);
                    }
                }
            }
        }
        static String reverse(String str){
            String string = "";
            for (int i = str.length()-1; i >= 0; i--) {
                string += str.charAt(i);
            }
            return string;
        }
        static Boolean sushu(int num){
            for (int i = 2; i < num; i++) {
                if (num%i == 0){        
                    return false;
                }else if (i == num -1){
                    return true;
                }
            }
            return true;
        }
    }
    

      

  • 相关阅读:
    python
    HTTP和HTTPS协议,详解
    常用加密算法之非对称加密算法
    Docker容器数据卷-Volume详解
    使用nsenter进入docker容器后端报错 mesg: ttyname failed: No such file or directory
    Docker 查看容器 IP 地址
    Docker容器数据卷volumes-from
    Docker 进入容器的4种方法
    Jmeter之Bean shell使用(二)
    Jmeter之Bean shell使用(一)
  • 原文地址:https://www.cnblogs.com/qzhc/p/12318539.html
Copyright © 2011-2022 走看看