<p>An <strong>ugly number</strong> is a positive integer whose prime factors are limited to <code>2</code>, <code>3</code>, and <code>5</code>.</p>

<p>Given an integer <code>n</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>ugly number</strong></em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 10
<strong>Output:</strong> 12
<strong>Explanation:</strong> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 1690</code></li>
</ul>

#define ll long long

class Solution {
public:
    vector<ll> f = {5,3,2};
    bool is_exact(ll n,ll f){
        if(n==1) return false;
        while(n%f==0) n/=f;
        return n==1;
    }
    vector<map<ll,ll>> memo;

    ll gf(ll n,ll it){
       // if(memo[it].find(n)!=memo[it].end()) return memo[it][n];

        ll cf = f[it];
        if(n<1) return 0; 

        //bool ie = is_exact(n,cf);
        ll mcit = log(n)/log(cf)+1;
        //if(!ie) mcit++;

        if(it==2) {
            //cout<<"n: "<<n<<" cf: "<<cf<<" mcit: "<<mcit<<" ans: "<<mcit<<"\n";
         //   memo[it][n] = mcit;
            return mcit;
        }
        ll ans = 0;
        for(ll i=0;i<=mcit;i++){
            ans += gf(n/pow(cf,i),it+1);
        }
        //cout<<"n: "<<n<<" cf: "<<cf<<" mcit: "<<mcit<<" ans: "<<ans<<"\n";
        // memo[it][n] = ans;
        return ans;
    }
    
    int nthUglyNumber(int n) {
        memo = vector<map<ll,ll>>(3);
        ll ans = 0;
        ll l = 1;
        ll r = 2e10;
        //cout<<gf(r,0)<<"\n";
        while(l<=r){
            ll m = (l+r)/2;

            ll cf = gf(m,0);
            ll pcf = gf(m-1,0);
            //cout<<"m: "<<m<<" cf: "<<cf<<" pcf: "<<pcf<<"\n";
            if(cf==n && pcf==n-1){
                ans = m;
                break;
            }
            if(cf>n) r = m-1;
            else if(cf<n) l = m+1;
            else if(pcf==n)  r = m-1;
        }
        return ans;
    }


};
8390