c語言:把只含因子2、3和5的數稱為醜數,求按從小到大的順序的第1500個醜數(兩種方法比較)

來源:互聯網
上載者:User

標籤:c語言 劍指offer 面試題 把只含因子2、3和5的數稱為醜數 求第1500個醜數 最佳化

把只含因子2、3和5的數稱為醜數,求按從小到大的順序的第1500個醜數。例如6、8都是醜數,但14不是,因為它包含因子7。習慣上把1當作第1個醜數。

演算法1:逐個判斷每個整數是不是醜數的解法,直觀但不夠高效

#include<stdio.h>


int ugly(int number)

{

while (number % 2 == 0)

{

number /= 2;

}

while (number % 3 == 0)

{

number /= 3;

}

while (number % 5 == 0)

{

number /= 5;

}

return (number == 1) ? 1 : 0;

}


int fun(int num)

{

if (num <= 0)

{

return 0;

}

int number = 0;

int uglyfound = 0;

while (uglyfound < num)

{

++number;

if (ugly(number))

{

++uglyfound;

}

}

return number;

}


int main()

{

int num = 0, ret = 0;

printf("請輸入一個醜數的序號:");

scanf("%d", &num);

ret = fun(num);

printf("number=%d\n", ret);

return 0;

}

演算法2:不需要在非醜數的整數上做任何計算,時間效率明顯提升,但是由於需要儲存已經產生的醜數,增加了空間消耗,相當於用空間消耗換取了時間效率的提升。主要代碼如下:

int Min(int number1, int number2, int number3);


int GetUglyNumber_Solution(int index)

{

if (index <= 0)

return 0;


int *pUglyNumbers = new int[index];

pUglyNumbers[0] = 1;

int nextUglyIndex = 1;


int *pMultiply2 = pUglyNumbers;

int *pMultiply3 = pUglyNumbers;

int *pMultiply5 = pUglyNumbers;


while (nextUglyIndex < index)

{

int min = Min(*pMultiply2 * 2, *pMultiply3 * 3, *pMultiply5 * 5);

pUglyNumbers[nextUglyIndex] = min;


while (*pMultiply2 * 2 <= pUglyNumbers[nextUglyIndex])

++pMultiply2;

while (*pMultiply3 * 3 <= pUglyNumbers[nextUglyIndex])

++pMultiply3;

while (*pMultiply5 * 5 <= pUglyNumbers[nextUglyIndex])

++pMultiply5;


++nextUglyIndex;

}


int ugly = pUglyNumbers[nextUglyIndex - 1];

delete[] pUglyNumbers;

return ugly;

}


int Min(int number1, int number2, int number3)

{

int min = (number1 < number2) ? number1 : number2;

min = (min < number3) ? min : number3;


return min;

}

結果:

請輸入一個醜數的序號:1500

number=859963392

請按任意鍵繼續. . .


本文出自 “岩梟” 部落格,請務必保留此出處http://yaoyaolx.blog.51cto.com/10732111/1743483

c語言:把只含因子2、3和5的數稱為醜數,求按從小到大的順序的第1500個醜數(兩種方法比較)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.