【问题标题】:Finding the Number of Primes between two numbers求两个数之间的素数
【发布时间】:2015-07-10 04:14:54
【问题描述】:
    public static void main(String[] args) {
        int a = 0;
        System.out.println(System.currentTimeMillis());
        for(int x = 2; x <=10000; x++) {
            boolean hasDivisor = false;
            for(int y = 2; y < x; y++) {
                if(x % y == 0) {
                    hasDivisor = true;
                }   
            }

            if(!hasDivisor) {
                System.out.println(a);
            }

        }
    }

}

这就是我的代码,我想让它在每次有素数时 int a 增加一,但我不知道在哪里放置 a++。我必须添加更多代码吗?

【问题讨论】:

标签: java primes


【解决方案1】:

试试这个代码... break 语句被添加并相应地递增 a++。

    public static void main(String[] args) {
    int a = 0;
    System.out.println(System.currentTimeMillis());
    for (int x = 2; x <= 10000; x++) {
        boolean hasDivisor = false;
        for (int y = 2; y < x; y++) {
            if (x % y == 0) {
                hasDivisor = true;
                break;
            }
        }

        if (!hasDivisor) {
            a++;
        }

    }
    System.out.println(a);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 2012-02-14
    • 2011-03-14
    • 2021-08-08
    相关资源
    最近更新 更多