Ugly Numbers STL练习C++题解
Time limit:3000 ms描述
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.
输入
There is no input to this program.
输出
Output should consist of a single line as shown below, with <number> replaced by the number computed.
题目大意
丑数是因子只有2、3或5的数字。序列
1,2,3,4,5,6,8,9,10,12,15,…
显示前11个丑数。按照惯例,1包括在内。
写一个程序来查找和打印第1500个丑数。
代码
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#define PI 3.14159265358979383246
#define LL long long
#define _for(i, a) for(size_t i = 0; i < (a); ++i)
#define _rep(i, a, b) for(size_t i = (a); i < (b); ++i)
using namespace std;
int min(const int a, const int b, const int c);
int main(void) {
int index = 1500;
int * map = new int[index];
int i = 0;
map[i] = 1;
int p2 = 0, p3 = 0, p5 = 0;
while (i < index - 1) {
while (map[p2++] * 2 <= map[i]);
while (map[p3++] * 3 <= map[i]);
while (map[p5++] * 5 <= map[i]);
map[++i] = min(map[--p2] * 2, map[--p3] * 3, map[--p5] * 5);
}
int ugly = map[i];
cout << "The 1500'th ugly number is " << ugly << '.' << endl;
return 0;
}
int min(const int a, const int b, const int c) {
return a < b ? (a < c ? a : c) : (b < c ? b : c);
}
本人也是新手,也是在学习中,勿喷
转载请注明出处
欢迎有问题的小伙伴一起交流哦~