Ugly Numbers
Ugly Numbers |
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 and Output
There is no input to this program. Output should consist of a single line as shown below, with <number> replaced by the number computed.
Sample output
The 1500'th ugly number is <number>.
题目的意思是要输出第1500个丑数,丑数的定义是不能被2 3 5之外的素数整除,那么问题来了,如果一个数是丑数,那么他目前的因子只有 2 3 5,那么当前的数乘2 3 5也是丑数。所以可以不断的由一个1生成好多的丑数,所以可以借用STL中的优先队列模板,但是同样的一个数可能会重复产生,比如15 会由 3*5 或5 *3生成,所以借用SET模板
代码如下
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<queue>
#include<stack>
#include<string>
#include<ctype.h>
#include<set>
#include<map>
#include<vector>
using namespace std;
//#include<windows.h>
//#include<conio.h>
#define Max(a,b) a>b?a:b
#define Min(a,b) a>b?b:a
#define mem(a,b) memset(a,b,sizeof(a))
int dir[4][2]= {{0,1},{0,-1},{1,0},{-1,0}},cf[3]={2,3,5};
int main()
{
priority_queue<long long,vector<long long >,greater<long long > >jb;
set<long long >sb;
jb.push(1);
sb.insert(1);
for(int i=1;;i++)
{
long long x=jb.top();
jb.pop();
if(i==1500)
{
printf("The 1500'th ugly number is %lld.\n",x);
break;
}
for(int j=0;j<3;j++)
{
long long k=x*cf[j];
if(!sb.count(k))
{
sb.insert(k);
jb.push(k);
}
}
}
return 0;
}
Ugly Numbers
Ugly Numbers |
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 and Output
There is no input to this program. Output should consist of a single line as shown below, with <number> replaced by the number computed.
Sample output
The 1500'th ugly number is <number>.