资讯专栏INFORMATION COLUMN

[LintCode] Kth Prime Number

z2xy / 2216人阅读

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;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68601.html

相关文章

  • [LintCode] Kth Smallest Number in Sorted Matrix

    Problem Find the kth smallest number in at row and column sorted matrix. Example Given k = 4 and a matrix: [ [1 ,5 ,7], [3 ,7 ,8], [4 ,8 ,9], ] return 5 Challenge O(k log n), n is the maximal n...

    mgckid 评论0 收藏0
  • [LintCode/LeetCode] Check Sum of K Primes

    Problem Given two numbers n and k. We need to find out if n can be written as sum of k prime numbers. Example Given n = 10, k = 2Return true // 10 = 5 + 5 Given n = 2, k = 2Return false Solution pub...

    lakeside 评论0 收藏0
  • [LintCode] Ugly Number

    Problem Write a program to check whether a given number is an ugly number`. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly ...

    raise_yang 评论0 收藏0
  • [LintCode/LeetCode] Super Ugly Number

    摘要:建两个新数组,一个存数,一个存。数组中所有元素初值都是。实现的过程是,一个循环里包含两个子循环。两个子循环的作用分别是,遍历数组与相乘找到最小乘积存入再遍历一次数组与的乘积,结果与相同的,就将加,即跳过这个结果相同结果只存一次。 Problem Write a program to find the nth super ugly number. Super ugly numbers a...

    wuyumin 评论0 收藏0
  • [LintCode] Kth Largest Element [PriorityQueue]

    摘要:可以不要用太简单的方法。先把它装满,再和队列顶端的数字比较,大的就替换掉,小的就。遍历完所有元素之后,顶部的数就是第大的数。 Problem Find K-th largest element in an array. Example In array [9,3,2,4,8], the 3rd largest element is 4.In array [1,2,3,4,5], the...

    Hwg 评论0 收藏0

发表评论

0条评论

z2xy

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<