Ugly number problem: optimized