题目
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 ‘’ replaced by the number
computed.
Sample Output
The 1500’th ugly number is .
题意
只要是把一个数分解,质因子只含有2,3,5的数,就为丑数。
解析
1.算法:我们知道一个较大的数可以分成两个质因子相乘,其中的质因子可能还可以分··· ···,所以我们倒推,以2,3,5为基数,这三个数任意若干次相乘构成的数是丑数也可以是构成丑数的质因子。
代码
#include<stdio.h>
int main()
{
long long u[1501];//定义数组,这个数组是储存丑数。
int i=1, j=1, k=1;
int a, b, c;
int mi;
int n;
u[i]=1; //第一个丑数是1.
for(n=2; n<1501; n++)//得出丑数,直到1500个。
{
a=2*u[i]; //以得到的丑数u[序号]乘以2,3,5这样的基数得到的还是丑数。
b=3*u[j];
c=5*u[k];
mi=a; //将丑数从小到大排序。
if(mi>b)
mi=b
if(mi>c)
mi=c;
u[n]=mi; //将a,b,c小的那个给本轮的u[n].
if(a==u[n]) i++;//判断最小的那个丑数在a,b,c,哪一个中,是的话,相应计数器+1,即下一轮a或者b或者c乘以丑数,成为新的质因子。
if(b==u[n]) j++;
if(c==u[n]) k++;
}
printf("The 1500'th ugly number is %d.\n",u[1500]);
return 0;
}