The Prime Directive answer

hello fellow coders I really need help/(solution for The Prime Directive)
all help appreciated. :dotted_line_face:

What are you having trouble with specifically?

my solution
// Import statement:
import java.util.ArrayList;

class PrimeDirective {
  
  // Add your methods here:
  public boolean isPrime(int number) {

    if (number == 2) { return true; }
    else if (number < 2) { return false; }

    for (int i = 2; i < number; i++ ) {
      if ((number % i) == 0) {
        return false; 
        //break;
      }
    }
    return true;
  }

  ArrayList<Integer> onlyPrimes(int[] numbers) {

    ArrayList<Integer> primes = new ArrayList<Integer>();
    for (int number: numbers) {
      if (isPrime(number)) {
        primes.add(number);
      }
    }
    return primes;
  }

  ArrayList<Integer> onlyPrimes(ArrayList<Integer> numbers) {

    ArrayList<Integer> primes = new ArrayList<Integer>();
    for (int number: numbers) {
      if (isPrime(number)) {
        primes.add(number);
      }
    }
    return primes;
  }

  // returns only first n primes in array:
  ArrayList<Integer> onlyPrimes(int[] numbers, int max_primes) {

    ArrayList<Integer> primes = new ArrayList<Integer>();
    int count = 0;
    for (int number: numbers) {
      if (isPrime(number)) {
        primes.add(number);
        count++;
      }
      if (count >= max_primes) {
        break;
      }
    }
    return primes;
  }
  
  
  public static void main(String[] args) {

    PrimeDirective pd = new PrimeDirective();
    int[] numbers = {6, 29, 28, 33, 11, 100, 101, 43, 89};
    /*
    System.out.println("7 " + pd.isPrime(7));
    System.out.println("28 " + pd.isPrime(28));
    System.out.println("2 " + pd.isPrime(2));
    System.out.println("0 " + pd.isPrime(0));

    for (int n : numbers) {
      System.out.print(n);
      System.out.print(" ");
      System.out.println(pd.isPrime(n));
    }
    */
    ArrayList<Integer> primes = pd.onlyPrimes(numbers);
    System.out.println(primes);
    System.out.println(pd.onlyPrimes(numbers, 3));
  }

}
1 Like

thanks so much for it . the project made no sense to me so I needed help.