Ugly Numbers(丑数)

本文介绍了一种高效算法来找出序列中的第N个丑数。丑数定义为仅包含质因数2、3和5的正整数,如1、2、3、4、5等。文章提供了一个C++实现示例,该程序能够快速计算出用户指定位置的丑数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




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, ... shows the first 10 ugly numbers. By convention, 1 is included. Given the integer n,write a program to find and print the n'th ugly number.

Input

Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.

Output

For each line, output the n’th ugly number .:Don’t deal with the line with n=0.

Sample Input

1
2
9
0

Sample Output

1
2
10














#include <iostream>#include <string.h>#include <cstdio>#include <algorithm>#include <string>using namespace std;long long min(long long a,long long b,long long c){ long long x=a<b?a:b; return x<c?x:c;}int main(){ long long num[1505]; long long p2,p3,p5; p2=p3=p5=1; memset(num,0,sizeof(num)); num[1]=1; int i=1; while(i<=1501){ num[++i]=min(num[p2]*2,num[p3]*3,num[p5]*5);if(num[i]==num[p2]*2) p2++;if(num[i]==num[p3]*3) p3++;if(num[i]==num[p5]*5) p5++; } int n; while(scanf("%d",&n)&&n){printf("%lld\n",num[n]); } return 0;}
### 丑数的概念 丑数是指仅包含质因数2、3和5的正整数。换句话说,任何丑数都可以表示为 \(2^a \times 3^b \times 5^c\) 的形式,其中 \(a\), \(b\), 和 \(c\) 是非负整数[^4]。按照惯例,1被认为是第一个丑数。 ### 如何用编程生成丑数 一种常见的方法是通过动态规划来生成丑数序列。这种方法利用了一个事实:每一个新的丑数必定是由之前的某个丑数分别乘以2、3或5得到的。因此可以通过维护三个指针(索引),分别对应于当前用于生成新丑数的基数,逐步构建整个丑数列表[^1]。 以下是基于此思路的一个Python实现: ```python def nth_ugly_number(n): ugly_numbers = [1] * n # 初始化长度为n的数组,初始值全设为1 index2, index3, index5 = 0, 0, 0 # 定义三个指针 next_multiple_of_2 = 2 next_multiple_of_3 = 3 next_multiple_of_5 = 5 for i in range(1, n): next_ugly = min(next_multiple_of_2, next_multiple_of_3, next_multiple_of_5) ugly_numbers[i] = next_ugly if next_ugly == next_multiple_of_2: index2 += 1 next_multiple_of_2 = ugly_numbers[index2] * 2 if next_ugly == next_multiple_of_3: index3 += 1 next_multiple_of_3 = ugly_numbers[index3] * 3 if next_ugly == next_multiple_of_5: index5 += 1 next_multiple_of_5 = ugly_numbers[index5] * 5 return ugly_numbers[-1] print(nth_ugly_number(10)) # 输出第10个丑数 ``` 上述代码实现了找到第\(n\)丑数的功能。它使用了三个变量存储下一个可能由2、3、5产生的丑数值,并通过比较这些候选者决定哪个是最小的新丑数。 ### 超级丑数简介 超级丑数是一个更广义的概念,指的是对于给定的一组质数集合中的任意组合所形成的数列。例如,在一组特定的质数如\[2, 7, 13, 19]\情况下,超级丑数就是能被这四个数之一完全分解的所有自然数[^2]。 #### 寻找超级丑数的方法 可以采用最小堆的数据结构来高效解决这个问题。基本思想是从1开始不断向堆中加入新的候选项直到获得所需的数量为止。每次取出堆顶元素作为当前最小子节点并将其与原始质数集相乘后的结果重新入队形成后续待选集合。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值