Problem:
The problem of ugly number is a common DP problem.
Description:
Ugly numbers are positive numbers whose prime factors only include 2,3,5,7. For example, 6,8 are ugly while 14 is not ugly since it includes another prime factor 7.Note that 1 is typically treated as an ugly number. courtesy: leetcode.com
#include <stdio.h>
#include <iostream>
using namespace std;
int _min(int a,int b,int c)
{
if(a<=b && a<=c)
{
return a;
}
if(b<=a && b<=c)
{
return b;
}
if(c<=b && c<=a)
{
return c;
}
}
int main()
{
int two_used=0,three_used=0,five_used=0;
int next_ugly_number;
int a,b,c;
int ugly[155];
ugly[0]=1;
for(int i=1;i<155;i++)
{
a = ugly[two_used]*2;
b = ugly[three_used]*3;
c = ugly[five_used]*5;
next_ugly_number = _min(a,b,c);
ugly[i]=next_ugly_number;
if(next_ugly_number==a)
two_used++;
if(next_ugly_number==b)
three_used++;
if(next_ugly_number==c)
five_used++;
}
//cout<<_min(5,2,3)<<endl;
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
cout<<ugly[n-1]<<endl;
}
return 0;
}