0

我需要使用嵌套的 for 循环来获取素数列表,代码如下:

public static void main(String[] args) {

        for (int i = 2; i <= 10; i++)
        {
            for (int d = 3; d <= 10; d = d + 2)
            {
                 int result = d % i;
                 System.out.println(result);

            }
        }
    }

我想我的逻辑就在这里,但结果有点不合时宜,请问有什么建议吗?

4

3 回答 3

4

像这样运行它,你会明白:

for (int i = 2; i <= 10; i++)
    {
        for (int d = 3; d <= 10; d = d + 2)
            {
                int result = d % i;
                System.out.println("i="+i+" d:"+d+" result:"+result);

            }
        }
    }
于 2012-11-05T20:20:11.460 回答
2

这是 Java 代码(算法使用Eratosthenes 的筛子):

public static void main(String[] args) { 
    int N = Integer.parseInt(args[0]);

    // initially assume all integers are prime
    boolean[] isPrime = new boolean[N + 1];
    for (int i = 2; i <= N; i++) {
        isPrime[i] = true;
    }

    // mark non-primes <= N using Sieve of Eratosthenes
    for (int i = 2; i*i <= N; i++) {

        // if i is prime, then mark multiples of i as nonprime
        // suffices to consider mutiples i, i+1, ..., N/i
        if (isPrime[i]) {
            for (int j = i; i*j <= N; j++) {
                isPrime[i*j] = false;
            }
        }
    }

    // count primes
    int primes = 0;
    for (int i = 2; i <= N; i++) {
        if (isPrime[i]) primes++;
    }
    System.out.println("The number of primes <= " + N + " is " + primes);
}

以上示例代码来自站点。

于 2012-11-05T20:24:01.907 回答
2

您正在做的只是与找出素数有关,因为您正在使用modulus运算符,这是必需的,但仅此而已。

您实际上需要利用该操作的结果。

您可以遵循以下内容pseudo-code:-

for i = 2 to 10 {

    1. set a boolean flag for prime to false;

    2. for j = 2 to (i - 1) {  // Since we just need to check modulus till that number
        1. check the result of `i % j`
        2. If any of the result in this loop is `0`, then `i` is not a prime number. 
           So, set the `prime` flag to false, and break out of loop, 
    }
    3. check the value of `prime` flag. If it is `true`, print number is `prime`. 
       Else print not prime 
}

我不会泄露代码,因为您自己尝试一下会有所帮助。您将学习如何实现以算法步骤形式给出的问题陈述。

于 2012-11-05T20:26:21.533 回答