bigpotato

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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, and n does not exceed 1690.

 

查找第n个ugly number,ugly number的含义详见上一篇263. Ugly Number

由于ugly number是一个质因数仅包含2、3、5的数,因此,若一个数是ugly number,它必然可以表示为(2^a)*(3^b)*(5^c),其中,a,b,c可取任意非负整数。用一个数组或容器从小到大依次记录第1到n个ugly number,输出第n个即可。

代码如下:

int nthUglyNumber(int n)
{
	vector<int> uglyNumbers;
	uglyNumbers.push_back(1);
	int ugly1 = 2, ugly2 = 3, ugly3 = 5, ugly = 1;
	int idx1 = 0, idx2 = 0, idx3 = 0;
	while ((int)uglyNumbers.size() < n)
	{
		ugly1 = uglyNumbers[idx1] * 2;
		ugly2 = uglyNumbers[idx2] * 3;
		ugly3 = uglyNumbers[idx3] * 5;
		ugly = (ugly1 < ugly2) ? (ugly1 < ugly3 ? ugly1 : ugly3) : (ugly2 < ugly3 ? ugly2 : ugly3);
		uglyNumbers.push_back(ugly);
		if (ugly1 == ugly)
			idx1++;
		if (ugly2 == ugly)
			idx2++;
		if (ugly3 == ugly)
			idx3++;
	}
	return ugly;
}

  

posted on 2018-03-19 00:20  bigpotato  阅读(113)  评论(0)    收藏  举报