Training 5 - F题
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, 15, …
shows the first 11 ugly numbers. By convention, 1 is included. Write a program to find and print the 1500’th ugly number.
Input
There is no input to this program.
Output
Output should consist of a single line as shown below, with ‘’ replaced by the number computed.
Sample Output
The 1500’th ugly number is .
#pragma warning (disable:4996)
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define inf 0X3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e7 + 5;
const int maxn = 2e5 + 5;
int t = 0;
int a = 1, b = 1, c = 1;
int ans[maxn];
void cal()
{
ans[++t] = 1;
while (t <= 1500)
{
int tmp = min(ans[a] * 2, min(ans[b] * 3, ans[c] * 5));
if (tmp == ans[a] * 2)
a++;
if (tmp == ans[b] * 3)
b++;
if (tmp == ans[c] * 5)
c++;
ans[++t] = tmp;
}
}
int main()
{
cal();
printf("The 1500'th ugly number is %d.\n", ans[1500]);
return 0;
}
思路:
dp,每一个新的数是之前的数乘以2、3、5,从小到大排列。