Skip to content

Commit

Permalink
Added UglyNumber dynamic programming in java
Browse files Browse the repository at this point in the history
  • Loading branch information
Priya997 authored and yshshrm committed Mar 13, 2020
1 parent a3c614e commit 5f20710
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions java/Dynamic Programming/UglyNumber.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import java.util.Scanner;

public class UglyNumber {
public static int helper_ugly(int n){
int[] ugly=new int[n+1];
ugly[0]=1;
int i2=0,i3=0,i5=0;
int next_multiple_2=2;
int next_multiple_3=3;
int next_multiple_5=5;
int next_num=1;
for(int i=1;i<n;i++)
{
next_num=Math.min(next_multiple_2,Math.min(next_multiple_3,next_multiple_5));
ugly[i]=next_num;
if(next_num==next_multiple_2)
{
i2++;
next_multiple_2=ugly[i2]*2;
}
if(next_num==next_multiple_3)
{
i3++;
next_multiple_3=ugly[i3]*3;
}
if(next_num==next_multiple_5)
{
i5++;
next_multiple_5=ugly[i5]*5;
}
}

return next_num;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println(helper_ugly(n));

}
}

0 comments on commit 5f20710

Please sign in to comment.