Solution for method that returns an ArrayList of the first n primes in an array

import java.util.ArrayList;
public class PrimeDirective{


  public boolean prime(int num){
    if(num == 2) return true;
    if(num<2) return false;

    for(int j=2;j<num;j++){
      if(num%j == 0){
        return false;
      }
    }
    return true;
  }


  public ArrayList<Integer> firstNPrime(int x, int[] numbers){
    ArrayList<Integer> nPrime = new ArrayList<Integer>();
    for(int k = 0; k< numbers.length; k++){
      this.prime(numbers[k]); // << number
      if(prime(numbers[k])){ // if number is Prime
        while(nPrime.size() < x){
          nPrime.add(numbers[k]);
          break;
        }
      
      }
    }
      return nPrime;
  }

  public static void main(String[] args){
    PrimeDirective pd = new PrimeDirective();

    int[] numbers = {6, 29, 28, 33, 11, 100, 101, 43, 89};

    System.out.println(pd.firstNPrime(3,numbers));


  }
}
2 Likes