Ugly Number

Rajat Jadam
1 min readMay 20, 2020

An ugly number is a number which is divisible by 2, 3, or 5 only.

Here is my dynamic programming approach to solve the problem.

#include <iostream>
#include<math.h>
#include<vector>
#include<stack>
#include<queue>
#include<bits/stdc++.h>
#include<limits.h>
using namespace std;
int calmin(int a,int b){
if(a<b){
return a;
}
else{
return b;
}
}
void ProduceArray(vector<int> &x,int max){
//cout<<”Inside Produce”<<max;
x[0]=0;
x[1]=1;
int i=2;
int n2=1;
int n3=1;
int n5=1;
while(i<=max){
//cout<<”\n”<<”Working”;
int a=2*x[n2];
int b=3*x[n3];
int c=5*x[n5];
int min=calmin(a,calmin(b,c));
x[i]=min;
if(min==a){
n2++;
}
if(min==b){
n3++;
}
if(min==c){
n5++;
}
i++;
}

}
int main() {
int TestCase;
cin>>TestCase;
int max=INT_MIN;
int A[TestCase];
for(int i=0;i<TestCase;i++){
cin>>A[i];
if(max<A[i]){
max=A[i];
}
}
vector<int> dp(max+1,0);
ProduceArray(dp,max);
for(int x:A){
cout<<dp[x]<<” “;
}
return 0;
}

--

--