求第1500个丑数

it2026-04-18  0

 丑数是指一个数被2或3或5整处的数,1默认为丑数。

例如:1,2,3,4,5,6,8,9,10,12,15

 

分解如下:

1,2(1x2),3(1x3),4(2x2),5(1x5),6(3x2),8(4x2),9(3x3),10(5x2),12(6x2),15

#include <stdio.h> int min(int a, int b, int c) { int tmp = a>b?b:a; return tmp > c?c:tmp; } void find_1500th_ugly() { int t2 = 0, t3 = 0, t5 = 0; int cnt = 0; int a[2000];//is ugly array a[0] = 1; while(1){ cnt ++; a[cnt] = min(a[t2]*2,a[t3]*3,a[t5]*5); //t2表示已经x2的已知的丑数位置 //t3表示已经x3的已知的丑数位置 while(a[t2]*2 <= a[cnt]){ t2++; } while(a[t3]*3 <= a[cnt]){ t3++; } while(a[t5]*5 <= a[cnt]){ t5++; } if(cnt == 1499){ printf("1500th ugly number is %ld\n",a[cnt]); break; } } return ; } int main() { find_1500th_ugly(); return 0; }

[root@localhost ugly]# ./ugly  1500th ugly number is 859963392

最新回复(0)