Ugly Numbers
2014-05-11 13:20
232 查看
题目描述
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ... shows the first 10 ugly numbers. By convention, 1 is included. Given the integer n,write a programto find and print the n‘th ugly number.
输入
Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.
输出
For each line, output the n’th ugly number .:Don’t deal with the line with n=0.
样例输入
1290
样例输出
1210解:
丑陋数是仅有素因子2、3、5的整数,1 * 2, 1 * 3, 1 * 5, 2 * 2, 2 * 3, 2 * 5……这样算下去,得到的是2, 3, 5, 4, 6, 10,而4应该排在5的前面,也就是说这样计算出来的值还要进行排序,感觉非常耗时间,怎么办呢?我们可以创建一个数组,把丑陋数的列表计算出来,然后通过输入值在数组中快速寻找出对应的值。我们得想办法进行动态排序,我们可以先设置3个变量来记录2的倍数、3的倍数、5的倍数的个数,将这些个数作为索引,找出丑陋数列表数组中对应的值,再乘以对应的2、3、5就可以得到现在需要插入列表的2的倍数、3的倍数、5的倍数的值,找到这三个值的最小的数,将这个数添加到数组的最后面,一直循环这个操作就可以实现动态排序了。可能我上面表达得不是很好,看代码应该就清楚了,代码如下:
#include <stdio.h> #define MAXN 1500 + 10 int twoNum = 0, threeNum = 0, fiveNum = 0; int ugly[MAXN]; void create() { ugly[0] = 1; for (int i = 1; i < 1500; i++) { int min = ugly[twoNum] * 2, b = ugly[threeNum] * 3, c = ugly[fiveNum] * 5; if (b < min) { min = b; } if (c < min) { min = c; } ugly[i] = min; if (ugly[i] == ugly[twoNum] * 2) { twoNum++; } if (ugly[i] == ugly[threeNum] * 3) { threeNum++; } if (ugly[i] == ugly[fiveNum] * 5) { fiveNum++; } } } int main() { create(); int n; while (scanf("%d", &n) != EOF) { if (n == 0) { return 0; } printf("%d\n", ugly[n - 1]); } return 0; }
相关文章推荐
- Linux C函数参考手册(PDF版)
- 动易2006序列号破解算法公布
- C#数据结构与算法揭秘二
- C#实现打造气泡屏幕保护效果
- C/C++数据对齐详细解析
- 浅析STL中的常用算法
- C 语言基础教程(我的C之旅开始了)[三]
- C 语言基础教程(我的C之旅开始了)[七]
- C/C++ 宏详细解析
- 用C#生成不重复的随机数的代码
- JavaScript 组件之旅(二)编码实现和算法
- 在c和c++中实现函数回调
- 浅析C/C++中被人误解的SIZEOF
- C 语言基础教程(我的C之旅开始了)[六]
- java数据结构和算法学习之汉诺塔示例
- python计数排序和基数排序算法实例
- python基础教程之python消息摘要算法使用示例
- C/C++函数调用的几种方式总结
- c/c++中变量的声明和定义深入解析