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.
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
参考博客地址:http://blog.csdn.net/chinaczy/article/details/5571692
//这道题求ugly num,由题意可以看出每个ugly number都只由2、3、5中的一个或几个因子相乘而得。算法如下:
//从第二个数字开始,每个数字可以有前一个数字乘2或乘3或乘5得到,而且这个数字是前一个数字乘2、乘3、乘5后得到的数字中的最小的一个
//每乘1个数,都要记录下这个数所乘的次数
#include <iostream>
using namespace std;
int main()
{
int n , i , m2 , m3 , m5 ; //m2 m3 m5 分别记录乘2、乘3、乘5的次数
long ugly_num[1505];
while( cin >> n && n != 0 )
{
m2 = m3 = m5 = 0 ; //初始所乘次数为零
ugly_num[0] = 1 ; //初始(第一个数字为1)数字为1
for(i=1;i<n;i++)
{
ugly_num[i] = min( 2 * ugly_num[m2] , min( 3 * ugly_num[m3] , 5 * ugly_num[m5] ) ) ;//求乘2、乘3、乘5后最小的数字并赋值给ugly_num
if(ugly_num[i] == 2 * ugly_num[m2] ) m2++ ; //记录所乘次数
if(ugly_num[i] == 3 * ugly_num[m3] ) m3++ ;
if(ugly_num[i] == 5 * ugly_num[m5] ) m5++ ;
}
cout<<ugly_num[n-1]<<endl;
}
return 0;
}