What is the 10 001st prime number?

120 阅读1分钟

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

Q: What is the 10001st prime number?

Train of thought

  • The even numbers is definitely not prime number. (expect 2)
  • Among odd numbers, using all multiply self of odd numbers that are less than an odd number as prime factors to judge whether this odd number is prime number

Solutions

public static void main(String[] args) {
    // calculate the quantity of prime numbers
    int count = 1;
    // only check odd numbers, expect 2
    int num = 3;

    // stop when count = 10001, return result
    while (count < 10001) {
        if (isPrime(num)) {
            count++;
        }
        num += 2;
    }
    // result should minus the 2 added above 
    System.out.println(num - 2); 
}

public static boolean isPrime(int num) {
    if (num <= 2) {
        return true;
    }
    if (num % 2 == 0) {
        return false;
    }
    // using all multiply self of odd numbers less than and equal an odd number to judge the prime number
    for (int i = 3; i * i <= num; i += 2) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

The complexity

Time complexity: O(n²)