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. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

public class Solution {
    public int nthUglyNumber(int n) {
        /*
         * There are three sublist of the ugly numbers: 
         * (1) 1*2, 2*2, 3*2, 4*2, 5*2  (1, 2, 3, 4, 5,... times 2) 
         * (2) 1*3, 2*3, 3*3, 4*3, 5*3  (1, 2, 3, 4, 5,... times 3)
         * (3) 1*5, 2*5, 3*5, 4*5, 5*5  (1, 2, 3, 4, 5,... times 5)
         */
         List<Integer> ll = new LinkedList<Integer>(); 
         //add 1 to ll 
         ll.add(1); 
         int i2 = 0, i3 = 0, i5 = 0;  
         while (ll.size() < n) {
             int m2 = ll.get(i2)*2;
             int m3 = ll.get(i3)*3;
             int m5 = ll.get(i5)*5;
             //the min of m2, m3, and m5 will be the next ugly number
             int next = Math.min(m2, Math.min(m3, m5));
             if (next == m2) i2++; 
             if (next == m3) i3++; 
             if (next == m5) i5++; 
             ll.add(next); 
         }
         return ll.get(ll.size()-1); 
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s