How to find the index of a prime number in JavaScript

1 Answer

0 votes
/**
 * Compute the prime at a given index.
 * Example: index 10 → 29, index 20 → 71
 *
 * This program uses:
 * - Clear naming that reflects intent
 * - A readable and efficient primality test
 * - Small, focused functions
 * - Straightforward control flow
 */

/**
 * Checks whether a number is prime.
 * Uses an efficient √n loop and skips even numbers after 2.
 */
function isPrime(value) {
  if (value < 2) return false;
  if (value === 2) return true;
  if (value % 2 === 0) return false;

  // Only test odd divisors up to √value
  const limit = Math.floor(Math.sqrt(value));
  for (let divisor = 3; divisor <= limit; divisor += 2) {
    if (value % divisor === 0) return false;
  }

  return true;
}

/**
 * Returns the prime at the given index (1‑based).
 * Example: 1 → 2, 2 → 3, 3 → 5, ...
 *
 * The function increments through integers,
 * counting primes until reaching the requested index.
 */
function primeAtIndex(index) {
  if (index < 1) {
    throw new Error("Index must be a positive integer.");
  }

  let count = 0;
  let candidate = 1;

  // Walk forward until we find the index‑th prime
  while (count < index) {
    candidate += 1;
    if (isPrime(candidate)) {
      count += 1;
    }
  }

  return candidate;
}

/**
 * main
 */

console.log("10 →", primeAtIndex(10));
console.log("20 →", primeAtIndex(20));
console.log("100 →", primeAtIndex(100));
console.log("1000 →", primeAtIndex(1000));
console.log("10000 →", primeAtIndex(10000));



/*
run:

10 → 29
20 → 71
100 → 541
1000 → 7919
10000 → 104729

*/

 



answered Aug 19 by avibootz
...