当我试图找出不丑的数字时,我遇到了一些问题.丑陋的数字是唯一的素数因子是2,3或5的数字.那么这个数字不是很难看?我试着找出1到100,000,000之间不难看的数字.我的程序可以解决问题,但似乎有点慢.我怎么能让它更快?这是代码:
#include <iostream>
#include <queue>
using namespace std;
typedef pair<unsigned long,int> node_type;
main()
{
//generates 1500 ugly numbers into result[];
unsigned long result[1500];
priority_queue<node_type,vector<node_type>,greater<node_type> > Q;
Q.push(node_type(1,2));
for(int i=0;i<1500;i++)
{
node_type node = Q.top();
Q.pop();
switch(node.second)
{
case 2:Q.push(make_pair(node.first*2,2));
case 3:Q.push(make_pair(node.first*3,3));
case 5:Q.push(make_pair(node.first*5,5));
}
result[i]=node.first;
}
/*****************************************************
//Here is the approach I used:
//The initial value of the integer k is 1;
//and will increase by 1 every time
//k will be checked if it's a ugly number,if not increase …Run Code Online (Sandbox Code Playgroud) c++ ×1