Ugly Number問題及其擴(kuò)展

首先,我們從最簡單的開始:

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 since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

Ugly Number是指 一個正數(shù)的素因子只包含2,3,5. 比如 6和8就是Ugly Number,而14不是, 14 = 2 * 7 多了另外一個素因子7. 所以判斷一個數(shù)字是不是Ugly Number就很簡單了,就是這幾個因子來回除。能整除就是Ugly Number,反之就不是。代碼如下:

    public boolean isUgly(int num) {
            if(num <= 0) return false;
            if(num == 1) return true;

            while (num > 1) {
                if (num % 2 == 0) {
                    num = num / 2;
                } else if(num % 3 == 0) {
                    num = num / 3;
                } else if (num % 5 == 0) {
                    num = num / 5;
                } else
                    return false;
            }
            return true;
        }

那么繼續(xù)考慮一個進(jìn)階問題:

Write a program to find the n-th Ugly Number.

Ugly Number are positive numbers whose prime factors only include 2,3, 5. For example, **1,2, 3, 4, 5, 6, 8, 9, 10, 12 **is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

我們升級一下來找一下第n個Ugly Number。對于任何一個Ugly Number k 那么 2 * k, 3 * k, 5 * k 都是Ugly Number。因此找第n個Ugly Number 就是,通過把一個Ugly Number跟素因子{2,3,5}乘積,不斷的按照數(shù)字大小增加到列表后面,直到找到第n個Ugly Number為止。

   public int nthUglyNumber(int n) {
        if(n == 1) return 1;
        int[] uglyNumbers = new int[n];
        uglyNumbers[0] = 1;
        int idx2 = 0;
        int idx3 = 0;
        int idx5 = 0;
        int counter = 1;
        while(counter < n) {
            int min = Math.min(
                      Math.min(uglyNumbers[idx2]*2, uglyNumbers[idx3] * 3),
                      uglyNumbers[idx5] * 5);

            if(min == uglyNumbers[idx2] * 2) {
                idx2++;
            }
            if(min == uglyNumbers[idx3] * 3) {
                idx3++;
            }
            if(min == uglyNumbers[idx5] * 5) {
                idx5++;
            }
            uglyNumbers[counter] = min;
            counter++;
        }
        return uglyNumbers[n -1];
    }

把這個更進(jìn)一步擴(kuò)展的更通用一點(diǎn):

Write a program to find the nth Super Ugly Number.

Super Ugly Numbers are positive numbers whose all prime factors are in the given prime list primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 Super Ugly Numbers given primes = [2, 7, 13, 19] of size 4.

Note:

(1) 1 is a super ugly number for any given primes.

(2) The given numbers in primes are in ascending order.

(3) 0 < k ≤ 100, 0< n ≤ 106, 0 < primes[i] < 1000.

原理同上不解釋,直接上代碼:

public int nthSuperUglyNumber(int n, int[] primes) {
        if( n == 1 ) return 1;

        ArrayList<Integer> uglyNumbers = new ArrayList<>();
        uglyNumbers.add(1);
        int[] index = new int[primes.length];
        for(int i = 0; i < index.length; i++) {
            index[i] = 0;
        }
        int counter = 1;
        while(counter < n) {
            int min = Integer.MAX_VALUE;
            int minIndex = 0;
            for (int i = 0; i < primes.length; i++) {
                int currentVal = uglyNumbers.get(index[i]) * primes[i];
                if(currentVal < min) {
                    min = currentVal;
                    minIndex = i;
                }
            }
            index[minIndex]++;
           if (uglyNumbers.get(uglyNumbers.size() -1 ) != min) {
              //這個判斷很重要,不然會有大量重復(fù)結(jié)果。
                uglyNumbers.add(min);
                counter++;
           }
        }
        return uglyNumbers.get(uglyNumbers.size() - 1);
    }

當(dāng)然了,我這個代碼寫的比較low,有高手7行代碼解決問題,膜拜一下:

    int nthSuperUglyNumber(int n, vector<int>& primes) {
        vector<int> index(primes.size(), 0), ugly(n, INT_MAX);
        ugly[0]=1;
        for(int i=1; i<n; i++){
            for(int j=0; j<primes.size(); j++)
                ugly[i]=min(ugly[i],ugly[index[j]]*primes[j]);
            for(int j=0; j<primes.size(); j++)
                index[j]+=(ugly[i]==ugly[index[j]]*primes[j]);
        }
        return ugly[n-1];
    }

Ugly Number 我們引申到質(zhì)數(shù)相關(guān)的經(jīng)典問題。

質(zhì)數(shù)(Prime Number)又稱素?cái)?shù),質(zhì)素定義為大于1的自然數(shù)中,除了1和它本身以外再有其他因數(shù)的數(shù)。

質(zhì)數(shù)問題有3個常見問題:

  1. 判斷一個數(shù)是否是質(zhì)數(shù);
  2. 給一個自然數(shù)N,打印出小于N的所有質(zhì)數(shù);
  3. 給一個自然數(shù)N,打印出前N個質(zhì)數(shù);

后兩個問題的答案以及效率跟第一個問題,即,你如何判斷一個數(shù)是質(zhì)數(shù)有關(guān)。

判斷一個數(shù)N是否是質(zhì)數(shù)最簡單的辦法是根據(jù)質(zhì)數(shù)的定義,通過不斷的除2 -- N-1之間的數(shù)字,看看是否能找到除1和自身之外的質(zhì)因子。

進(jìn)一步觀察發(fā)現(xiàn)除了2之外質(zhì)數(shù)一定是奇數(shù),因?yàn)樗械呐紨?shù)一定有質(zhì)因子 2

再通過觀察發(fā)現(xiàn)只要嘗試3 -- N-1的開平方之間的數(shù)字就夠了,因?yàn)橐驍?shù)都是成對出現(xiàn)的,比如:100 : 1 * 100 , 2 * 50, 4 * 25,5 * 20, 10 * 10 ,因此只要嘗試到10就夠了。

    bool isPrime(int n) {
        if(n < 2) return false;
        if(n == 2) return true;
        for(int i = 3; i*i <= n; i += 2)
             if(n%i == 0) return false;
        return true;
    }

最后,說一個求質(zhì)數(shù)比較牛逼的方法,篩除法

這個方法是牛逼的數(shù)學(xué)家埃拉托斯特尼(Eratosthenes) 公元前276年--前194年提出的。

就是這個小老頭

埃拉托斯特尼篩法.png

這個人有多牛逼呢,說個小成就吧,設(shè)計(jì)了經(jīng)緯度,并且在2000多年前,用數(shù)學(xué)的方法測量出了地球直徑。

說回 篩除法

因?yàn)?strong>2是質(zhì)數(shù),因此可以把2的倍數(shù)全部去掉;

接著往下數(shù)3是質(zhì)數(shù),把3的倍數(shù)全部去掉;

繼續(xù)數(shù)最小的數(shù)是5,把5的倍數(shù)全部去掉,依此類推再把7的倍數(shù)全部去掉。這樣不斷的篩除,最后就把素?cái)?shù)剩下了。

可能說的比較抽象,我們用動圖來演示一下:

篩法演示圖.gif

偽代碼如下

    Input: an integer n > 1
    Let A be an array of Boolean values, indexed by integers 2 to n,
    initially all set to true.
        for i = 2, 3, 4, ..., not exceeding √n:
            if A[i] is true:
                for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n:
                    A[j] := false
    Output: all i such that A[i] is true.

PS. Markdown 很好用

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容