Back to General discussions forum
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class PrimeNumbersGeneration {
public static int findIndex(int a){
ArrayList<Integer> list = new ArrayList<>();
boolean [] isComposite = new boolean [200000 + 1]; // limit + 1 because we won't use '0'th index of the array
isComposite[1] = true;
// Mark all composite numbers
for (int i = 2; i <= 200000; i++) {
if (!isComposite[i]) {
// 'i' is a prime number
list.add(i);
int multiple = 2;
while (i * multiple <= 200000) {
isComposite [i * multiple] = true;
multiple++;
}
}
}
return list.get(a);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Cases: ");
int size = in.nextInt();
for (int i = 0; i < size; i++){
int p = in.nextInt();
System.out.print(findIndex(p) + " ");
}
}
That is my code above and I need the first 200000 prime numbers can someone please help me? This is problem 61 and I have no idea what im doing wrong.
Hi,
I don't claim to understand Java, but it looks like your code creates the list of primes each time the findIndex function is called. It would be better to create the list of primes just once.
Also, from the example data, you can see that the 199999th prime is 2750131, so your list of primes needs to go further than 2750131, but it looks like your list stops at 200000.