Ugly Numbers STL练习C++题解

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);
}

本人也是新手,也是在学习中,勿喷

转载请注明出处

欢迎有问题的小伙伴一起交流哦~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值