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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
#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; } |