Problem Description
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 '<number>' replaced by the number computed.
SampleOutput
The 1500'th ugly number is <number>.
题目大意:
丑数是指不能被2,3,5以外的其他素数整除的数。把丑数从小到大排列起来
结果如下:
1,2,3,4,5,6,8,9,10,12,15,…
求第1500个丑数
思路:
一般暴力求解那肯定会T,所以我们可以借助优先队列将其进行优化,注意的是需要用long long 型,这大家应该也都知道多嘴了ヾ(=゚・゚=)ノ喵♪。
具体看代码:
#include<iostream> #include<cstdio> #include<queue> #include<vector> using namespace std; #define ll long long const int maxx=1501; int main() { ll a,b,c; //优先队列 priority_queue<ll,vector<ll>,greater<ll> >q; q.push(1);//初始化为 1; int num=0;//计数; ll ans; while(num<maxx) { ans=q.top(); q.pop(); num++; if(num==1500) { printf("The 1500'th ugly number is %d.\n", ans); break; } //如果ans 为ugly ,则2*ans,3*ans,5*ans都是丑数; a=ans*2; b=ans*3; c=ans*5; // a 如果与 b或c是同一数的因数关系,那么该数一定在b或c中出现过 // 因为b或c比a大 if((a%5)&&(a%3)) { q.push(a); } if((b%5)) { q.push(b); } q.push(c); } return 0; }
还有一种操作就是下面这种o(゚Д゚)っ啥!,前提是已经知道结果:
#include<iostream> using namespace std; int main() { cout<<"The 1500'th ugly number is 859963392.\n"; }