Question: 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.
Given a number n
, the task is to find n’th
Ugly number.
(https://www.geeksforgeeks.org/ugly-numbers/)
Answer: The Dynamic Programming approach in the above link
Psuedocode:
1 Declare an array for ugly numbers: ugly[n]
2 Initialize first ugly no: ugly[0] = 1
3 Initialize three array index variables i2, i3, i5 to point to
1st element of the ugly array:
i2 = i3 = i5 =0;
4 Initialize 3 choices for the next ugly no:
next_mulitple_of_2 = ugly[i2]*2;
next_mulitple_of_3 = ugly[i3]*3
next_mulitple_of_5 = ugly[i5]*5;
5 Now go in a loop to fill all ugly numbers till 150:
For (i = 1; i < 150; i++ )
{
/* These small steps are not optimized for good
readability. Will optimize them in C program */
next_ugly_no = Min(next_mulitple_of_2,
next_mulitple_of_3,
next_mulitple_of_5);
ugly[i] = next_ugly_no
if (next_ugly_no == next_mulitple_of_2)
{
i2 = i2 + 1;
next_mulitple_of_2 = ugly[i2]*2;
}
if (next_ugly_no == next_mulitple_of_3)
{
i3 = i3 + 1;
next_mulitple_of_3 = ugly[i3]*3;
}
if (next_ugly_no == next_mulitple_of_5)
{
i5 = i5 + 1;
next_mulitple_of_5 = ugly[i5]*5;
}
}/* end of for loop */
6.return next_ugly_no
Doubts:
I don't understand the DP approach in this case.
- What are the subproblems?
- What is the recursion in this case?
- How are the subproblems overlapping?
Why do we keep track of current ugly number? Why not just go through the multiples of 2,3,5 and each point keep taking minimum.
Like 2,3,5. Then 4,3,5, Then 4,6,5..keeps incrementing the multiples of each.
Related Question: nth ugly number ( I weent through the answers but I was confused in the above questions I mentioned.)