Find the 10001st Prime Number

  • 时间:2020-09-10 12:55:33
  • 分类:网络文摘
  • 阅读:75 次

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?

Test Prime Number

A prime number has exactly two factors: 1 and itself. Thus we can write a quick prime testing function. Please note that we only need to test up to Square Root of N, as if we find factor a, there will be N/a.

1
2
3
4
5
6
7
8
function isPrime(n) {
    if (n <= 1) return false;
    if (n == 2) return true;
    for (let i = 2; i * i <= n; ++ i) {
        if (n % i == 0) return false;
    }
    return true;
}
function isPrime(n) {
    if (n <= 1) return false;
    if (n == 2) return true;
    for (let i = 2; i * i <= n; ++ i) {
        if (n % i == 0) return false;
    }
    return true;
}

The runtime complexity is O(Sqrt(N)).

Find the N-th Prime Number

Then, we can then compute the N-th prime number using the following:

1
2
3
4
5
6
7
8
9
10
11
12
function findNthPrime(N) {
  let prime = 2;
  let i = 1;
  while (i < N) {
    do {
        prime ++;
    } while (!isPrime(prime));
    i ++;
  }
  return prime;
}
console.log(findNthPrime(10001));
function findNthPrime(N) {
  let prime = 2;
  let i = 1;
  while (i < N) {
    do {
        prime ++;
    } while (!isPrime(prime));
    i ++;
  }
  return prime;
}
console.log(findNthPrime(10001));

The answer is 104743.

We can improve a little bit, as we know that prime numbers cannot be even except 2, thus we can skip two intead of one.

1
2
3
4
5
6
7
8
9
10
11
12
13
function findNthPrime(N) {
    if (N == 1) return 2;
    if (N == 2) return 3;
    let prime = 3;
    let i = 2;
    while (i < N) {
      do {
          prime += 2;
      } while (!isPrime(prime));
      i ++;
    }
    return prime;
  }
function findNthPrime(N) {
    if (N == 1) return 2;
    if (N == 2) return 3;
    let prime = 3;
    let i = 2;
    while (i < N) {
      do {
          prime += 2;
      } while (!isPrime(prime));
      i ++;
    }
    return prime;
  }

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
Boost the Visibility of Your Blog With In-Person Events  Are Top 20 Witnesses Voting Each Other? Introducing Witness-voti  How to Design a Browser History using Double-ended Queue (deque)  SteemJs: How Many Witnesses are Running on 23.1?  Illustrating the Blockchain via SteemJs – Blocks are Chain  DFS and BFS Algorithms to Find All the Lonely Nodes of a Binary   Three ways of Running a continuous NodeJS Application on Your Se  K Closest Points to Origin using Custom Sorting Algorithm in C++  Using Hash Set to Determine if a String is the Permutation of An  Recursive Algorithm to Get Proxy Votes on Steem Blockchain 
评论列表
添加评论