首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >显示回文素数

显示回文素数
EN

Stack Overflow用户
提问于 2019-03-01 06:03:53
回答 1查看 1.8K关注 0票数 0

我正在尝试做一个程序来显示前50个质数回文,每行有10个数字。这是我到目前为止所拥有的代码,但是当运行时什么都没有发生。我已经寻找过类似的解决方案,但似乎找不到错误所在。任何帮助都将不胜感激。

代码语言:javascript
复制
 import java.lang.Math;
public class PalindromicPrime {
    public static void main(String[] args) {
        int counter = 1;
        int start = 2;      

        isPalindrome(start);
        isPrime(start);

        while (counter <= 50) {
            if (isPrime(start) && isPalindrome(start)) {
                System.out.print(start + " ");
                if (counter % 10 == 0) {
                    System.out.println();
                    counter++;
                }
                start++;
            }
        }
    }
    public static boolean isPalindrome(int x) {
        int reverse = 0;
        while(x > 0) {
        reverse = reverse * 10 + x % 10;
        x = x / 10;
        }
        if (reverse == x) {
            return true;
        }
        else {
            return false;
        }       
    }
    public static boolean isPrime(int x) {
        if (x % 2 == 0 && x != 2) {
            return false;
        }

        int sqr = (int)Math.sqrt(x);
        for (int i = 3; i <= sqr; i += 2) {
            if(x % i == 0) {
                return false;
            }
        }
        return true;
    }

}
EN

回答 1

Stack Overflow用户

发布于 2019-03-01 06:27:35

你的代码是一个无限循环。这是因为您在if语句中增加了start,所以只有当start是质数和回文数字时才会递增。如果start不是回文或质数,它将不会进入条件,因此counter将Nevers递增并达到50

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54934978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档