不明白为什么我的素数代码不起作用

时间:2015-02-10 02:47:07

标签: java

class primeNumb {
    public static void main(String args[]) {

        int x;
        int m; 

        for (x = 0; x < 100; x++){    
            for (m = 0; m < 100; m++)    
                if ( (x / m == 1) && (x % m == 0) ) {    
                    System.out.println(x + "is a prime num");
                }
        }
    }
}

因此发现100以下的所有素数。对于外部循环中的每一个,内部循环大约为99x。在针对外部循环的这些内部99计算中的每一个期间,它询问问题,如果数字的除数是= 1,如果为真,则询问是否存在余数。就像一个素数如何只能被它自己和1分开一样,但对于那一部分,我们不需要计算。如果结果为真,则打印结果,将其标​​记为素数。对??我错过了什么?代码似乎不打印任何空白区域。我的逻辑是否正确?

2 个答案:

答案 0 :(得分:0)

我想你的代码应该是这样的:

    for (x = 3; x < 100; x++) { // start from 3, there is no sense to check 0,1,2
        boolean isPrime = true;
        for (m = 2; m < x; m++) // start from 2 and up to X
            if (x % m == 0) { // x can be divided by m -> not prime
                isPrime = false; break; // stop inner loop
            }
        if (isPrime) System.out.println("["+x+"] is prime");
    }

注意:这不是最佳方式,只是为了表明你的错误

答案 1 :(得分:0)

三件事: 首先,如果x < 3,打印出X是Prime,然后继续。

其次,如果你试图找出m是x的因子,即x%m == 0,那么X不是素数。

第三,您需要将m检查为仅高达sqrt(x)的因子。即,m <= sqrt(x)。

检查此代码。

public class PrimeNumber {

    public static void main(String[] args) {
        for (int x = 1; x < 100; x++){   
            boolean isPrime = true;;
            if (x < 4) {
                System.out.println(x + " is a prime num");
                continue;
            }
            for (int m = 2; m <1+ Math.sqrt(x); m++)    {
                if ( x % m == 0)  {    
                    //System.out.println(x + " is a NOT prime num");
                    isPrime = false;
                    break;
                }
            }

            if (isPrime) {    
                System.out.println(x + " is  prime num");
            }
        }   

    }

}

输出:

1 is a prime num
2 is a prime num
3 is a prime num
5 is  prime num
7 is  prime num
11 is  prime num
13 is  prime num
17 is  prime num
19 is  prime num
23 is  prime num
29 is  prime num
31 is  prime num
37 is  prime num
41 is  prime num
43 is  prime num
47 is  prime num
53 is  prime num
59 is  prime num
61 is  prime num
67 is  prime num
71 is  prime num
73 is  prime num
79 is  prime num
83 is  prime num
89 is  prime num
97 is  prime num