88分Java求助

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

java_practice @ 2024-12-03 23:29:20

测试点9超时了

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        for ( int i = a; i <= b; i ++ ){
            if ( isHw(i) ){
                    if ( isPrime(i) ){
                        System.out.println(i);
                    }
            }   
        }
    }
    public static boolean isPrime(int m){
        if ( m == 2 ){
            return true;    // 2要特判
        }
        else {
            for ( int i = 2; i*i <= m; i ++ ){
                if ( m % i == 0 ){
                    return false;
                }
            }
            return true;
        }
    }
    public static boolean isHw(int n){
        String str = String.valueOf(n);
        char[] a = str.toCharArray();
        for ( int i = 0; i < a.length; i ++ ){
            if ( a[i] != a[a.length-1-i] ){
                return false;
            }
        }
        return true;
    }
}

|