Write a program to find Nth Ugly Number - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Tuesday 9 July 2019

Write a program to find Nth Ugly Number



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, 15, … shows the first 11 ugly numbers. By convention, 1 is included. Write a program to find Nth Ugly Number.
Input:
The first line of input contains an integer T denoting the number of test cases. T testcases follow. For each testcase there is one line of input that contains the number N.

Output:
Print the Nth Ugly Number.
Constraints:
1 ≤ T ≤ 104
1 ≤ N ≤ 104
In this question all getting TLE or time limit exceeded
this is because we are calculating nth ugly number for every test case separately. we can store the ugly numbers for all n=1 to 10000 beforehand and then for every test case just print the nth ugly numbe





#include <iostream>

using namespace std;


void getuglyno(unsigned n,long long unsigned ugly[]){
   long long unsigned nuglyno=1,nmul2=2,nmul3=3,nmul5=5,i2=0,i3=0,i5=0;
    ugly[0]=1;
    for(unsigned i=1;i<n;i++){
        nuglyno=min(nmul2,min(nmul3,nmul5));
        ugly[i]=nuglyno;
        if(nuglyno==nmul2){
            i2++;
            nmul2=ugly[i2]*2;
               }
          if(nuglyno==nmul3){
            i3++;
            nmul3=ugly[i3]*3;
            }
            if(nuglyno==nmul5){
                i5++;
                nmul5=ugly[i5]*5;
            }
    }
}

int main() {
//code
int t;
cin>>t;

      long long unsigned ugly[10000];
      getuglyno(10000,ugly);
while(t--){
    int  x;
    cin>>x;
    cout<<ugly[x-1]<<endl;
}
return 0;
}