嵌套的“for”循环,混乱的结果

时间:2012-11-05 20:16:00

标签: java

我需要使用嵌套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);

            }
        }
    }

我想我的逻辑就在这里,但结果有点不在意,有什么建议吗?

3 个答案:

答案 0 :(得分: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);

            }
        }
    }

答案 1 :(得分:2)

这是Java代码(算法使用Sieve of 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);
}

以上示例代码来自this网站。

答案 2 :(得分: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 
}

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