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