JAVA Luogu B2139 True prime numbers in the interval

Problem Description
Find all true prime numbers between the positive integers M and N (N is not less than M).

The definition of a true prime number: If a positive integer P is a prime number, and its reverse order is also a prime number, then P is a true prime number.

For example, 11 and 13 are both true prime numbers, because the reverse order of 11 is still 11, and the reverse order of 13 is 31, which is also a prime number.

Input format:
Enter two numbers M and N, separated by spaces.

Output format
: Output the true prime numbers between M and N (including M and N) in ascending order, separated by commas. If there are no true primes in between, output No.

Input and output example
input

10 35

output

11,13,17,31

Description/Tip
1≤M≤N≤100000
source code

import java.util.Scanner;

public class Main{
    
    
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		int m = sc.nextInt();
		if(m==1) m=2;
		int n = sc.nextInt();
		int[] prime = new int[n-m+1];//存储素数
		int k = 0;//prime数组的下标
		int[] result = new int[n-m+1];//存储输出结果
		int r = 0;//result数组的下标
		//生成m和n之间的素数
		for(int i=m;i<=n;i++) {
    
    
			boolean flag = true;
			for(int j=2;j<=Math.sqrt(i);j++) {
    
    
				if(i%j==0) {
    
    
					flag = false;
					break;
				}
			}
			if(flag) {
    
    
				prime[k]=i;
				k++;
			}
		}
		//判断是不是真素数
		for(int i=0;i<k;i++) {
    
    
			String strprime = "";
			if(prime[i]!=0 && prime[i]>9) {
    
    
				Integer tmp = prime[i];
				String str = tmp.toString();//将整形转换成字符串
				for(int j=str.length()-1;j>=0;j--) {
    
    
					String ch = str.substring(j,j+1);//逆序取出字符
					strprime += ch;//构造逆序字符串
				}
				Integer retmp = new Integer(strprime);//将字符串转换成字符
				boolean flag2 = true;
				//判断逆序的数是不是素数
				for(int j=2;j<=Math.sqrt(retmp);j++) {
    
    
					if(retmp%j==0) {
    
    
						flag2 = false;
						break;
					}
				}
				if(flag2) {
    
    
					result[r] = prime[i];//将结果存储到数组里面
					r++;
				}
			}
		}
		//输出结果
		if(r==0) {
    
    
			System.out.println("No");
		}else {
    
    
			for(int i=0;i<r;i++) {
    
    
				if(result[i]!=0) {
    
    
					System.out.print(result[i]);
					if(i<r-1) {
    
    //如果不是最后一个元素则输出逗号
						System.out.print(",");
					}
				}
			}
		}	
	}
}

Guess you like

Origin blog.csdn.net/weixin_46574356/article/details/122644901