nthPrime function

int nthPrime(
  1. int n
)

Returns the nth prime number. The nth prime number is the number that holds the nth position in the list of prime numbers.

Example:

print(nthPrime(3));  // Output: 5
print(nthPrime(5));  // Output: 11
print(nthPrime(10));  // Output: 29

Implementation

int nthPrime(int n) {
  if (n < 1) throw ArgumentError('n must be greater than 0');
  if (n == 1) return 2; // Handle the 1st prime separately

  List<int> primes = [];
  for (int i = 2; primes.length < n; i++) {
    if (isPrime(i)) {
      primes.add(i);
    }
  }
  return primes.last;
}