码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode-Kth Prime Number.

时间:2014-12-25 08:43:45      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:

Design an algorithm to find the kth number such that the only prime factors are 3, 5, and 7.

The eligible numbers are like 3, 5, 7, 9, 15 ...

Example

If k=4, return 9.

Challenge

O(n log n) or O(n) time

Analysis:

This is the Humble number problem (丑数问题). Search the Humble Number problem online.

Solution:

 1 class Solution {
 2     /**
 3      * @param k: The number k.
 4      * @return: The kth prime number as description.
 5      */
 6     public long kthPrimeNumber(int k) {
 7         if (k==0) return 1;
 8         
 9         long[] res = new long[k+1];
10         res[0] = 1;
11         int p3 = 0, p5 = 0, p7 = 0;
12         for (int i=1;i<=k;i++){
13             //find the minimum prime number.
14             long val = Math.min(res[p3]*3, res[p5]*5);
15             val = Math.min(val, res[p7]*7);
16             if (val / res[p3] == 3) p3++;
17             if (val / res[p5] == 5) p5++;
18             if (val / res[p7] == 7) p7++;
19             res[i] = val;
20         }
21         return res[k];
22     }
23 };

 

LintCode-Kth Prime Number.

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/4183814.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!