题目:我们把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第1500个丑数。
答:
#include "stdafx.h" #include <iostream> using namespace std; //1、从1开始穷举,直到第1500个丑数,效率太低 //判断number是否为丑数 bool IsUgly(int number) { while (number % 2 == 0) { number = number / 2; } while (number % 3 == 0) { number = number / 3; } while (number % 5 == 0) { number = number / 5; } return number == 1; } //寻找第index个丑数 int FindUglyOne(int index) { if (index <= 0) { return -1; } int count = 0; int number = 0; while (count < index) { number++; if (IsUgly(number)) { count++; } } return number; } int MinNumber(int a, int b, int c) { a = a < b ? a : b; a = a < c ? a : c; return a; } //2、从丑数递推生成其他丑数 long FindUglyTwo(int index) { if (index <= 0) { return -1; } int *arr = new int[index]; arr[0] = 1; int index2 = 0; int index3 = 0; int index5 = 0; int count = 1; int ugly; while (count < index) { ugly = MinNumber(arr[index2] * 2, arr[index3] * 3, arr[index5] * 5); arr[count] = ugly; while(arr[index2] * 2 <= ugly) { index2++; } while(arr[index3] * 3 <= ugly) { index3++; } while(arr[index5] * 5 <= ugly) { index5++; } count++; } ugly = arr[count - 1]; delete [] arr; return ugly; } int _tmain(int argc, _TCHAR* argv[]) { cout<<FindUglyOne(1500)<<endl; cout<<FindUglyTwo(1500)<<endl; return 0; }
运行界面如下: