Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

arrays - Generating primes using nested loops (java). Problem with loops

I already generated primes using the Sieve of Eratosthenes algorithm (I asked about it here Sieve of Eratosthenes, generating primes. Problem with loops)

But now I have to do it using only an array and nested loops. I tried to apply this approch https://examples.javacodegeeks.com/java-basics/for-loop/generate-prime-numbers-with-for-loop/, but I can't get why it doesn't work correctly for me I just want to check if a number is prime and add it to my array Could u help me pls?

public class Part6 {

    public static  int[] primeSequence(int n) {
        int[] primes = new int[n];

        for (int i = 2; i < n; i++) {
            boolean isPrimeNumber = true;
            for (int j = i + 1; j < i; j++) {
            if(j % i == 0)
                isPrimeNumber = false;
            break;
            }
            if (isPrimeNumber)
                primes[i] = i;
        }
       return  primes;
        }


    public static void main(String[] args) {
        for (int number : primeSequence(Integer.parseInt(args[0]))) {
            System.out.print(number);
        }

    }
    
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are missing braces in your inner loop, your inner loop doesn't get executed (int j = i + 1; j < i!), the order of operands in the modulo operation is wrong and the inner loop should probably start at 2.

        for (int j = 2; j < i; j++) {
        if(i % j) == 0){
             isPrimeNumber = false;
             break; 
            }
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...