zoukankan      html  css  js  c++  java
  • LintCode-Kth Prime Number.

    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.

    分析:假设数组ugly[N]中存放不断产生的丑数,初始只有一个丑数ugly[0]=1,由此出发,下一个丑数由因子2,3,5竞争产生,得到 ugly[0]*2, ugly[0]*3, ugly[0]*5, 显然最小的那个数是新的丑数,所以第2个丑数为ugly[1]=2,开始新一轮的竞争,由于上一轮竞争中,因子2获胜,这时因子2应该乘以ugly[1] 才显得公平,得到ugly[1]*2,ugly[0]*3,ugly[0]*5, 因子3获胜,ugly[2]=3,同理,下次竞争时因子3应该乘以ugly[1],即:ugly[1]*2, ugly[1]*3, ugly[0]*5, 因子5获胜,得到ugly[3]=5,重复这个过程,直到第n个丑数产生。总之:每次竞争中有一个(也可能是两个)因子胜出,下一次竞争中 胜出的因子就 应该加大惩罚!

    注意这里不可以使用if/else 循环,因为有可能多于一个指针的结果是相等的:例如p3->5, p5->3, 他们的结果相等,这是两个指针都要+1

    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 };
  • 相关阅读:
    中国式沟通
    10 表连接优化
    09 优化数据访问
    07 SQL优化技术
    06 执行计划
    04 系统和对象统计信息
    03 找出性能问题
    02 key concept
    Xpert 调优
    JavaWeb_常用功能_01_文件上传
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4183814.html
Copyright © 2011-2022 走看看