Primes and sorted

isPrime

private boolean isPrime(int n, ArrayList<Integer> primes) {
  for (int d : primes) {
    if (d > Math.sqrt(n)) return true;
    if (n % d == 0) return false;
  }
  return true;
}

This is no longer general purpose so I made it private.

It assumes you aren’t going to call it with anything less than 2 and that the primes argument is always a list of all the primes less than n.

primes

public ArrayList<Integer> primes(int number) {
  ArrayList<Integer> primes = new ArrayList<>();
  int n = 2;
  while (primes.size() < number) {
    if (isPrime(n, primes)) primes.add(n);
    n++;
  }
  return primes;
}

A good use for a while loop since we don’t know how many times we need to iterate but we do know when we’re done.

Note also that you can just use size(); no need for an extra count variable which many of you used.

isSorted

public boolean isSorted(ArrayList<Integer> list) {
  for (int i = 0; i < list.size() - 1; i++) {
    if (list.get(i) > list.get(i + 1)) return false;
  }
  return true;
}

Note the non-canonical loop, with the upper bound size() - 1 rather than size().

This is a pretty common way to process adjacent pairs in a list (or similarly in an array or String).