Ugly Numbers
来源:互联网 发布:cf抽奖算法 编辑:程序博客网 时间:2024/05/19 17:48
题目描述
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 program to 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 + 10int 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;}
1 0
- Ugly Numbers
- Ugly numbers
- Ugly Numbers
- Ugly Numbers
- Ugly Numbers
- Ugly Numbers
- Ugly Numbers
- Ugly Numbers
- Ugly Numbers
- Ugly Numbers
- ugly numbers
- Ugly Numbers
- problem 1338: ugly numbers
- pku_1338 Ugly Numbers
- 1751: Ugly Numbers
- pku 1338 Ugly Numbers
- POJ 1338 Ugly Numbers
- POJ 1338 Ugly Numbers
- 终端之1_对终端进行读写
- 忘记 Linux虚拟机的密码
- 进程和线程
- CSS样式导入的三个方法
- 堆和栈的区别(转过无数次的文章)
- Ugly Numbers
- UVA 10312 - Expression Bracketing(数论+Catalan数)
- Linux find命令详解和实例说明
- contextlib——上下文管理
- 【JavaWeb】基础知识总结05 jQuery
- POJ 1003
- C# 创建自定义转换
- UVA 10497 - Sweet Child Makes Trouble(DP+高精度)
- 飞鸽传书文件记录选择CFile还是CStdioFile?