1751: Ugly Numbers

本文介绍了一个寻找第1500个丑数的算法实现,丑数是指只包含2、3和5这三个质因数的整数。通过使用C++中的堆排序,该算法高效地生成了所需的丑数。

 


StatusIn/OutTIME LimitMEMORY LimitSubmit TimesSolved UsersJUDGE TYPE
stdin/stdout3s8192K1038322Standard

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>.

 

 


This problem is used for contest: 112 

 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
   int i;
   double x,ugly[1501];
   vector<double> heap(1);
   heap[0]=-1; 
   for(i=1;i<=1500;i++)
   {
      x=heap[0],ugly[i]=-x;
      pop_heap(heap.begin(),heap.end());
      heap.pop_back();
      if(find(heap.begin(),heap.end(),x*2)==heap.end())
      {
    heap.push_back(x*2);
    push_heap(heap.begin(),heap.end());
   }
   if(find(heap.begin(),heap.end(),x*3)==heap.end())
   {
    heap.push_back(x*3);
    push_heap(heap.begin(),heap.end());
   }
   if(find(heap.begin(),heap.end(),x*5)==heap.end())
   {
    heap.push_back(x*5);
    push_heap(heap.begin(),heap.end()) ;
   }
}
    printf("The 1500'th ugly number is %.0lf./n",ugly[1500]) ;
    return 0 ;
}

丑数是指只包含质因子 235 的数,习惯上把 1 当做第一个丑数。以下是几种用 C++ 实现求解丑数的方法: ### 方法一:逐个判断法 这种方法是对每个数进行判断,看它是否只包含质因子 235。 ```cpp #include <iostream> bool isUgly(int num) { if (num <= 0) return false; while (num % 2 == 0) num /= 2; while (num % 3 == 0) num /= 3; while (num % 5 == 0) num /= 5; return num == 1; } void findUglyNumbers(int n) { for (int i = 1; i <= n; ++i) { if (isUgly(i)) { std::cout << i << " 是丑数" << std::endl; } } } int main() { int n = 20; findUglyNumbers(n); return 0; } ``` ### 方法二:动态规划法 根据丑数的定义,丑数应该是另一个丑数乘以 23 或者 5 的结果(1 除外)。因此可以创建一个数组,里面的数字是排好序的丑数,里面的每一个丑数是前面的丑数乘以 23 或者 5 得到的 [^1]。 ```cpp #include <iostream> #include <vector> #include <algorithm> int nthUglyNumber(int n) { std::vector<int> uglyNumbers(n); uglyNumbers[0] = 1; int p2 = 0, p3 = 0, p5 = 0; for (int i = 1; i < n; ++i) { int nextUgly = std::min({uglyNumbers[p2] * 2, uglyNumbers[p3] * 3, uglyNumbers[p5] * 5}); uglyNumbers[i] = nextUgly; if (nextUgly == uglyNumbers[p2] * 2) ++p2; if (nextUgly == uglyNumbers[p3] * 3) ++p3; if (nextUgly == uglyNumbers[p5] * 5) ++p5; } return uglyNumbers[n - 1]; } int main() { int n = 10; std::cout << "第 " << n << " 个丑数是: " << nthUglyNumber(n) << std::endl; return 0; } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值