Ugly Number II - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Friday 21 August 2020

Ugly Number II

Ugly Number II

 Ugly Number II

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5

Example:

Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note:  

  1. 1 is typically treated as an ugly number.
  2. n does not exceed 1690.
class Solution {
public:
    
    
    int nthUglyNumber(int n) {
      int a[n];
        a[0]=1;
        int ind2=0,ind3=0,ind5=0;
        
        for(int i=1;i<n;++i)
        {
              a[i]=min(a[ind2]*2,min(a[ind3]*3,a[ind5]*5));
            if(a[i]==(a[ind2]*2))++ind2;
            if(a[i]==a[ind3]*3)++ind3;
            if(a[i]==a[ind5]*5)++ind5;
          
        }
        return a[n-1];
     
    }
};