首页 > 代码库 > [LintCode] Kth Prime Number

[LintCode] Kth Prime Number

http://lintcode.com/en/problem/kth-prime-number/#

class Solution {
    /**
     * @param k: The number k.
     * @return: The kth prime number as description.
     */
    public long kthPrimeNumber(int k) {
        // write your code here
        
        Queue<Long> q3 = new LinkedList<>();
        q3.offer(3L);
        Queue<Long> q5 = new LinkedList<>();
        q5.offer(5L);
        Queue<Long> q7 = new LinkedList<>();
        q7.offer(7L);
        
        long v = 0;
        for (int i = 0 ; i < k ; i ++)
        {
            // Find min element from 3 tops.
            if (q3.peek() < q5.peek() && q3.peek() < q7.peek())
            {
                v = q3.poll();
                q3.offer(v * 3);
                q5.offer(v * 5);
                q7.offer(v * 7);
            }
            else if (q5.peek() < q3.peek() && q5.peek() < q7.peek())
            {
                v = q5.poll();
                q5.offer(v * 5);
                q7.offer(v * 7);
            }
            else
            {
                v = q7.poll();
                q7.offer(v * 7);
            }
        }
        return v;
    }
};


[LintCode] Kth Prime Number