首页 > 编程语言 > 详细

算法题2-输出某个范围的回文素数

时间:2020-03-22 00:32:17      阅读:98      评论:0      收藏:0      [点我收藏+]

素数:除了1和本身 不能被其他数整除的数

回文数:一个数反转之后和原来的数相等

思路

1.判断一个数是否为素数(两层for循环,外层是遍历该范围 内层是判断该数是否为素数)

2.在为素数的基础上判断是否为回文数  然后利用计数器

3.调用方法进行测试

代码:


import java.util.Scanner;
public class Test02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//输入范围
int a = scanner.nextInt();
System.out.print("\t");
int b = scanner.nextInt();
//计数
int count = 0;
count = method01(a, b);
System.out.println();
System.out.println(count + "");
scanner.close();

}

//判断一个数为回文素数 返回个数
public static int method01(int a, int b) {
int count = 0;//计数
//遍历
for (int i = a; i <= b; i++) {
boolean bool = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) { //不是素数
bool = false;
}
}
if (bool && isHuiwen(i)) {
System.out.print(i + "\t");
count++;
}
}
return count;
}

//判断一个数是否为回文数
private static boolean isHuiwen(int i) {
boolean bool = false;
String str = String.valueOf(i);
//将整型转换为字符串类型
int R = str.length() - 1;
int L = 0;
while (L < R) { //遍历
if (str.charAt(L) == str.charAt(R)) {
bool = true;
}
L++;
R--;
}
return bool;
}

 

算法题2-输出某个范围的回文素数

原文:https://www.cnblogs.com/yindong2019/p/12543347.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!