Problem

Given the prime number n, output the number of prime numbers

Notice

n <= 100000
The prime number is defined as a natural number greater than 1, and there are no other factors except 1 and it itself.

Example

Given n = 3, return 2.

explanation:
[2,3,5], 3 is the second prime number.
Given n = 11, return 5.

explanation:
[2,3,5,7,11], 11 is the fifth prime number.

Solution

public class Solution {
    /**
     * @param n: the number
     * @return: the rank of the number
     */
    public int kthPrime(int n) {
        // write your code here
        int num = 0;
        for (int i = 1; i < n; i++) {
            boolean isPrime = true;
            for (int j = 1; j < i; j++) {
                if (j != 1 && i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                num++;
            }
        }
        return num;
    }
}

linspiration
161 声望53 粉丝