Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 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 Reply

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; 
            }
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[2] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...