丑数:只有2 3 5 这三个因子的数,求前(第)1500个。习惯上我们把1当作第一个丑数
例如 6, 8是丑数。14不是。
#include <stdio.h> int Min(int x,int y, int z){ int min = (x <= y) ? x : y; return min = (z <= min) ? z : min; } int GetUglyNumber(int index){ if(index <= 0){ return 0; } int* uglyNumbers= new int[index]; int uglyCount = 1; uglyNumbers[0] = 1; int* ugly2 = uglyNumbers; int* ugly3 = uglyNumbers; int* ugly5 = uglyNumbers; for(; uglyCount< index; ++uglyCount){ int min = Min((*ugly2)*2,(*ugly3)*3,(*ugly5)*5); uglyNumbers[uglyCount] = min; while((*ugly2)*2 <= min){ ++ugly2; } while((*ugly3)*3 <= min){ ++ugly3; } while((*ugly5)*5 <= min){ ++ugly5; } } for(int i=0; i<index; i++){ printf("%d ",uglyNumbers[i]); } delete[] uglyNumbers; } int main(){ int index = 1500; GetUglyNumber(index); return 0; }
gcc uglyNumber.cpp
1
2
3
4
5
6
8
9
10
12
15
16
18
20
24
25
27
30
32
36
.
.
.
786432000
787320000
791015625
796262400
797161500
800000000
805306368
806215680
810000000
816293376
819200000
820125000
829440000
838860800
839808000
843750000
849346560
850305600
854296875
859963392
第1500个为 859963392