标签:
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 ...
If k=4, return 9.
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 };
标签:
原文地址:http://www.cnblogs.com/lishiblog/p/4183814.html