您的位置:首页 > 其它

Ugly Number II

2015-09-05 18:46 267 查看
Write a program to find the n-th ugly number.

Ugly numbers 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.

int min(int num1, int num2, int num3)

{

int temp = num1 > num2 ? num2 : num1;
return temp > num3 ? num3 : temp;


}

int nthUglyNumber(int n) {

if (n <= 0)
return 0;
int *nums = (int *)malloc(sizeof(int)*n);
nums[0] = 1;

int *temp2 = nums;
int *temp3 = nums;
int *temp5 = nums;

int i = 1;
while (i < n)
{
int temp = min(*temp2*2, *temp3*3, *temp5*5);
nums[i] = temp;

while(*temp2*2 <= nums[i])
temp2++;
while(*temp3*3 <= nums[i])
temp3++;
while(*temp5*5 <= nums[i])
temp5++;

i++;
}

int res = nums[n-1];
free(nums);

return res;


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: