题目描述
Problem Description
如果一个正整数最多只包含2,3,5,7这四种素因子,则称这个正整数为丑数。数列1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27就是前20个丑数。
给定一个n,请编程输出第n个丑数。
Input
输入包含多组测试用例。
每组测试用例包含一个整数n(1 <= n <= 5842),输入为0时,表示测试数据的结束。
Output
对于每组的n,请输出第n个丑数。
每组输出占一行。
输入样例
1
2
3
4
11
12
13
21
22
23
100
1000
5842
0
输出样例
1
2
3
4
12
14
15
28
30
32
450
385875
2000000000
题目分析
易得后面的元素均是由前面的元素与2,3,5,7相乘所得。
代码如下:
#include <bits/stdc++.h>
using namespace std;
int n = 1;
int a[7001];
int t2, t3, t5, t7;
int main(){
a[0] = 1;
t2 = t3 = t5 = t7 = 0;
for (int i = 1; i < 5843; i++)
{
a[i] = min(min(a[t2]*2, a[t3]*3), min(a[t5]*5, a[t7]*7));
if (a[i] == a[t2] * 2) t2 ++;
if (a[i] == a[t3] * 3) t3 ++;
if (a[i] == a[t5] * 5) t5 ++;
if (a[i] == a[t7] * 7) t7 ++;
}
while(n){
scanf("%d", &n);
if(!n) break;
printf("%d\n", a[n - 1]);
}
return 0;
}