# Ugly Number

Problem I

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

public class Solution {
public boolean isUgly(int num) {
if (num <= 0) {
return false;
}
while (num > 1) {
if (num % 2 == 0) {
num /= 2;
continue;
}
if (num % 3 == 0) {
num /= 3;
continue;
}
if (num % 5 == 0) {
num /= 5;
continue;
}
return false;
}
return true;
}
}


Problem 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) {
if (n <= 0) {
return 0;
}

List<Integer> list = new ArrayList<Integer>();

int i2 = 0, i3 = 0, i5 = 0;

while (list.size() < n) {
int n2 = list.get(i2) * 2;
int n3 = list.get(i3) * 3;
int n5 = list.get(i5) * 5;
int m = Math.min(Math.min(n2, n3), n5);

if (m == n2) {
++i2;
}
if (m == n3) {
++i3;
}
if (m == n5) {
++i5;
}