An ugly number is a positive integer whose only prime factors are 2, 3, and 5, with 1 included by convention. The sequence begins as 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, and so on. Given an integer n, return the nth ugly number.
Examples:
Input: n = 5
Output: 5
Explanation: Ugly Numbers - 1, 2, 3, 4, 5, 6, 8, 9, 10, 12.
So, 5th Ugly Number is 5.Input: n = 10
Output: 12
Explanation: 12 is the 10th ugly number.
Table of Content
[Naive Approach] - Using Iteration - Exponential Time and O(1) Space
The idea is to loop over all positive integers starting from 1 until the count of ugly numbers in less than n. To check if number is ugly, divide the number by greatest divisible powers of 2, 3 and 5, if the number becomes 1 then it is an ugly number otherwise not.
// C++ program to find nth ugly number
#include <bits/stdc++.h>
using namespace std;
// This function divides a by greatest
// divisible power of b
int maxDivide(int a, int b)
{
while (a % b == 0)
a = a / b;
return a;
}
// Function to check if a number is ugly or not
int isUgly(int val)
{
val = maxDivide(val, 2);
val = maxDivide(val, 3);
val = maxDivide(val, 5);
return (val == 1) ? 1 : 0;
}
// Function to get the nth ugly number
int uglyNumber(int n)
{
int i = 1;
// Ugly number count
int count = 1;
// Check for all integers until ugly
// count becomes n
while (n > count)
{
i++;
if (isUgly(i))
count++;
}
return i;
}
int main()
{
int n = 10;
cout << uglyNumber(n);
return 0;
}
#include <stdio.h>
// This function divides a by greatest
// divisible power of b
int maxDivide(int a, int b)
{
while (a % b == 0)
a = a / b;
return a;
}
// Function to check if a number is ugly or not
int isUgly(int val)
{
val = maxDivide(val, 2);
val = maxDivide(val, 3);
val = maxDivide(val, 5);
return (val == 1) ? 1 : 0;
}
// Function to get the nth ugly number
int uglyNumber(int n)
{
int i = 1;
// Ugly number count
int count = 1;
// Check for all integers until ugly
// count becomes n
while (n > count)
{
i++;
if (isUgly(i))
count++;
}
return i;
}
int main()
{
int n = 10;
printf("%d", uglyNumber(n));
return 0;
}
// This function divides a by greatest
// divisible power of b
class GfG {
// This function divides a by greatest
// divisible power of b
static int maxDivide(int a, int b)
{
while (a % b == 0)
a = a / b;
return a;
}
// Function to check if a number is ugly or not
static int isUgly(int val)
{
val = maxDivide(val, 2);
val = maxDivide(val, 3);
val = maxDivide(val, 5);
return (val == 1) ? 1 : 0;
}
// Function to get the nth ugly number
static int uglyNumber(int n)
{
int i = 1;
// Ugly number count
int count = 1;
// Check for all integers until ugly
// count becomes n
while (n > count) {
i++;
if (isUgly(i) == 1)
count++;
}
return i;
}
public static void main(String[] args)
{
int n = 10;
System.out.println(uglyNumber(n));
}
}
# This function divides a by greatest
# divisible power of b
def maxDivide(a, b):
while a % b == 0:
a = a // b
return a
# Function to check if a number is ugly or not
def isUgly(val):
val = maxDivide(val, 2)
val = maxDivide(val, 3)
val = maxDivide(val, 5)
return 1 if val == 1 else 0
# Function to get the nth ugly number
def uglyNumber(n):
i = 1
# Ugly number count
count = 1
# Check for all integers until ugly
# count becomes n
while n > count:
i += 1
if isUgly(i):
count += 1
return i
if __name__ == "__main__":
n = 10
print(uglyNumber(n))
// This function divides a by greatest
// divisible power of b
using System;
class GfG {
// This function divides a by greatest
// divisible power of b
static int maxDivide(int a, int b)
{
while (a % b == 0)
a = a / b;
return a;
}
// Function to check if a number is ugly or not
static int isUgly(int val)
{
val = maxDivide(val, 2);
val = maxDivide(val, 3);
val = maxDivide(val, 5);
return (val == 1) ? 1 : 0;
}
// Function to get the nth ugly number
static int uglyNumber(int n)
{
int i = 1;
// Ugly number count
int count = 1;
// Check for all integers until ugly
// count becomes n
while (n > count) {
i++;
if (isUgly(i) == 1)
count++;
}
return i;
}
static void Main()
{
int n = 10;
Console.WriteLine(uglyNumber(n));
}
}
// This function divides a by greatest
// divisible power of b
function maxDivide(a, b)
{
while (a % b === 0)
a = a / b;
return a;
}
// Function to check if a number is ugly or not
function isUgly(val)
{
val = maxDivide(val, 2);
val = maxDivide(val, 3);
val = maxDivide(val, 5);
return (val === 1) ? 1 : 0;
}
// Function to get the nth ugly number
function uglyNumber(n)
{
let i = 1;
// Ugly number count
let count = 1;
// Check for all integers until ugly
// count becomes n
while (n > count) {
i++;
if (isUgly(i))
count++;
}
return i;
}
let n = 10;
console.log(uglyNumber(n));
Output
12
Time Complexity: The time complexity is O(n^(1/3) * exp(n^(1/3))) since ugly numbers are sparse, and the nth ugly number is approximately exp(n^(1/3)). As a result, the loop runs up to exp(n^(1/3)) times, with each check taking O(n^(1/3)) time, leading to the overall complexity.
Space Complexity: O(1)
[Better Approach] - Using Sorted Set - O(n * log n) Time and O(n) Space
The idea is to use Set (set in C++, TreeSet in Java) to store the unique ugly numbers in sorted order. To do so, firstly insert the first ugly number i.e. 1 in the set and run a loop until the Nth ugly number is not found. At each iteration take out the smallest number x from the set, and insert three numbers (x * 2), (x * 3), and (x * 5), representing the next three ugly numbers. At last return the Nth number in the set.
#include <bits/stdc++.h>
using namespace std;
// Function to get the nth ugly number
int uglyNumber(int n)
{
// to store the ugly numbers in sorted order
set<long long> s; // Use long long to prevent overflow
// insert the first ugly number i.e. 1.
s.insert(1);
n--;
while (n)
{
long long x = *(s.begin()); // Use long long
s.erase(s.begin());
s.insert(x * 2);
s.insert(x * 3);
s.insert(x * 5);
// Decrement n
n--;
}
// return the first element of the set, which is the nth ugly number
return *(s.begin());
}
int main()
{
int n = 10;
cout << uglyNumber(n);
return 0;
}
import java.util.*;
public class Main {
// Function to get the nth ugly number
static int uglyNumber(int n)
{
TreeSet<Long> s
= new TreeSet<>(); // Use TreeSet<Long> to store
// ugly numbers
s.add(1L); // Add the first ugly number
n--;
while (n > 0) {
long x
= s.first(); // Get the smallest ugly number
s.remove(x); // Remove it from the set
s.add(x * 2);
s.add(x * 3);
s.add(x * 5);
n--;
}
// Return the nth ugly number (casted to int)
return s.first().intValue();
}
public static void main(String[] args)
{
int n = 10;
System.out.println(uglyNumber(n)); // Output: 12
}
}
# Function to get the nth ugly number
def uglyNumber(n):
# to store the ugly numbers in sorted order
# (using a list to simulate a sorted set)
s = [1]
n -= 1
# loop until n becomes 0
while n:
x = s[0]
s.pop(0)
if x * 2 not in s:
s.append(x * 2)
if x * 3 not in s:
s.append(x * 3)
if x * 5 not in s:
s.append(x * 5)
# sort the list to maintain sorted order
s.sort()
# Decrement n
n -= 1
# return the first element of the set
# which is the nth ugly number
return s[0]
if __name__ == "__main__":
n = 10
print(uglyNumber(n))
using System;
using System.Collections.Generic;
class GfG {
// Function to get the nth ugly number
static int uglyNumber(int n)
{
SortedSet<long> s
= new SortedSet<long>(); // Use long to prevent
// overflow
s.Add(1); // Insert the first ugly number
n--;
while (n > 0) {
long x = s.Min; // Get the smallest ugly number
s.Remove(x); // Remove it from the set
s.Add(x * 2);
s.Add(x * 3);
s.Add(x * 5);
n--;
}
// Return the nth ugly number (casted to int)
return (int)s.Min;
}
static void Main()
{
int n = 10;
Console.WriteLine(uglyNumber(n)); // Output: 12
}
}
// Function to get the nth ugly number
function uglyNumber(n)
{
// to store the ugly numbers in sorted order
// (using an array to simulate a sorted set)
let s = [ 1 ];
// insert the first ugly number i.e. 1.
n--;
// loop until n becomes 0
while (n > 0) {
let x = s[0];
// Deleting the first element
s.shift();
s.push(x * 2);
s.push(x * 3);
s.push(x * 5);
// Remove duplicates and sort the array
s = Array.from(new Set(s));
s.sort(function(a, b) { return a - b; });
// Decrement n
n--;
}
// return the first element of the set
// which is the nth ugly number
return s[0];
}
let n = 10;
console.log(uglyNumber(n));
Output
12
[Expected Approach 1 ] - Using Dynamic Programming O(n) Time and O(n) Space
The ugly number sequence consists of numbers that can only be divided by 2, 3, or 5, starting with 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, …. One way to view this sequence is by breaking it into three groups:
- Multiples of 2 → (1×2, 2×2, 3×2, …)
- Multiples of 3 → (1×3, 2×3, 3×3, …)
- Multiples of 5 → (1×5, 2×5, 3×5, …)
To generate ugly numbers efficiently, we maintain an array dp
[]of size n, initializing dp[0] = 1(the first ugly number). Additionally, we use:
- Three index pointers to track the next multiple of 2, 3, and 5.
- Three variables to store these next multiples.
Initially, the index pointers are set to 0, and the multiples are set to 2, 3, and 5. For each iteration from 1 to n, we:
- Select the smallest among the three multiples as the next ugly number.
- Store this number in dp
[].- Update the corresponding index and compute its next multiple using
arr[ind] * factor, where the factor is 2, 3, or 5.
Illustration: Finding the 5th Ugly Number
#include <bits/stdc++.h>
using namespace std;
// Function to get the nth ugly number
int uglyNumber(int n)
{
// To store ugly numbers
vector<int> arr(n);
// stores the index of the next
// multiple of 2, 3, and 5.
int ind2 = 0, ind3 = 0, ind5 = 0;
int mulTwo = 2, mulThree = 3, mulFive = 5;
int nextNum = 1;
arr[0] = 1;
// loop to fill up the array up to n
for (int i = 1; i < n; i++)
{
// find the minimum of the multiples
nextNum = min({mulTwo, mulThree, mulFive});
arr[i] = nextNum;
// if nextNum is equal to any of the multiples
// then increment the value of the multiple
if (nextNum == mulTwo)
{
ind2++;
mulTwo = arr[ind2] * 2;
}
if (nextNum == mulThree)
{
ind3++;
mulThree = arr[ind3] * 3;
}
if (nextNum == mulFive)
{
ind5++;
mulFive = arr[ind5] * 5;
}
}
// return the nth ugly number
return nextNum;
}
int main()
{
int n = 10;
cout << uglyNumber(n);
return 0;
}
// Function to get the nth ugly number
import java.util.*;
class GfG {
// Function to get the nth ugly number
static int uglyNumber(int n)
{
// To store ugly numbers
int[] arr = new int[n];
// stores the index of the next
// multiple of 2, 3, and 5.
int ind2 = 0, ind3 = 0, ind5 = 0;
// to next multiple of 2, 3, and 5
int mulTwo = 2, mulThree = 3, mulFive = 5;
// stores next ugly number
int nextNum = 1;
// 1 is the first ugly number
arr[0] = 1;
// loop to fill up the array up to n
for (int i = 1; i < n; i++) {
// find the minimum of the multiples
nextNum = Math.min(mulTwo,
Math.min(mulThree, mulFive));
arr[i] = nextNum;
// if nextNum is equal to any of the multiples
// then increment the value of the multiple
if (nextNum == mulTwo) {
ind2++;
mulTwo = arr[ind2] * 2;
}
if (nextNum == mulThree) {
ind3++;
mulThree = arr[ind3] * 3;
}
if (nextNum == mulFive) {
ind5++;
mulFive = arr[ind5] * 5;
}
}
// return the nth ugly number
return nextNum;
}
public static void main(String[] args)
{
int n = 10;
System.out.println(uglyNumber(n));
}
}
# Function to get the nth ugly number
def uglyNumber(n):
# To store ugly numbers
arr = [0] * n
# stores the index of the next
# multiple of 2, 3, and 5.
ind2 = 0
ind3 = 0
ind5 = 0
# to next multiple of 2, 3, and 5
mulTwo = 2
mulThree = 3
mulFive = 5
# stores next ugly number
nextNum = 1
# 1 is the first ugly number
arr[0] = 1
# loop to fill up the array up to n
for i in range(1, n):
# find the minimum of the multiples
nextNum = min(mulTwo, mulThree, mulFive)
arr[i] = nextNum
# if nextNum is equal to any of the multiples
# then increment the value of the multiple
if nextNum == mulTwo:
ind2 += 1
mulTwo = arr[ind2] * 2
if nextNum == mulThree:
ind3 += 1
mulThree = arr[ind3] * 3
if nextNum == mulFive:
ind5 += 1
mulFive = arr[ind5] * 5
# return the nth ugly number
return nextNum
if __name__ == "__main__":
n = 10
print(uglyNumber(n))
// Function to get the nth ugly number
using System;
class GfG {
// Function to get the nth ugly number
static int uglyNumber(int n)
{
// To store ugly numbers
int[] arr = new int[n];
// stores the index of the next
// multiple of 2, 3, and 5.
int ind2 = 0, ind3 = 0, ind5 = 0;
// to next multiple of 2, 3, and 5
int mulTwo = 2, mulThree = 3, mulFive = 5;
// stores next ugly number
int nextNum = 1;
// 1 is the first ugly number
arr[0] = 1;
// loop to fill up the array up to n
for (int i = 1; i < n; i++) {
// find the minimum of the multiples
nextNum = Math.Min(mulTwo,
Math.Min(mulThree, mulFive));
arr[i] = nextNum;
// if nextNum is equal to any of the multiples
// then increment the value of the multiple
if (nextNum == mulTwo) {
ind2++;
mulTwo = arr[ind2] * 2;
}
if (nextNum == mulThree) {
ind3++;
mulThree = arr[ind3] * 3;
}
if (nextNum == mulFive) {
ind5++;
mulFive = arr[ind5] * 5;
}
}
// return the nth ugly number
return nextNum;
}
static void Main()
{
int n = 10;
Console.WriteLine(uglyNumber(n));
}
}
// Function to get the nth ugly number
function uglyNumber(n)
{
// To store ugly numbers
let arr = new Array(n).fill(0);
// stores the index of the next
// multiple of 2, 3, and 5.
let ind2 = 0, ind3 = 0, ind5 = 0;
// to next multiple of 2, 3, and 5
let mulTwo = 2, mulThree = 3, mulFive = 5;
// stores next ugly number
let nextNum = 1;
// 1 is the first ugly number
arr[0] = 1;
// loop to fill up the array up to n
for (let i = 1; i < n; i++) {
// find the minimum of the multiples
nextNum
= Math.min(mulTwo, Math.min(mulThree, mulFive));
arr[i] = nextNum;
// if nextNum is equal to any of the multiples
// then increment the value of the multiple
if (nextNum === mulTwo) {
ind2++;
mulTwo = arr[ind2] * 2;
}
if (nextNum === mulThree) {
ind3++;
mulThree = arr[ind3] * 3;
}
if (nextNum === mulFive) {
ind5++;
mulFive = arr[ind5] * 5;
}
}
// return the nth ugly number
return nextNum;
}
let n = 10;
console.log(uglyNumber(n));
Output
12
[Expected Approach 2 ] - Using Binary Search - O((log r) ^ 3) Time and O(1) Space
Note: This approach works best when we know the highest possible value of the ugly number. In our case, we are considering the maximum possible value to be 21474836647.
The idea is to use binary search to find the value such that the count of ugly numbers up to that value is equal to n. To do so, firstly create an array power[] of size 31, to store the power of 2 raised up to 30, this will be used to calculate the number of ugly numbers. Now perform binary search, taking low as 1, and high as 21474836647, which we are considering to be highest possible ugly number. At each iteration find the mid value.
Now, to calculate the count of ugly numbers up to mid value, use nested loops where outer loop increase in multiple of 5, and the inner loop increase in multiple of 3. For each iteration find the index of the first value greater than mid / i * j, (where i is multiple of 5, and j is multiple of 3) in array powers[]. Increment the count by the index.
At last check if count is greater than or equal to n, if so, update the answer to mid, and reduce high to mid - 1, otherwise increase low to mid + 1.
#include <bits/stdc++.h>
using namespace std;
// Function to get the nth ugly number
int uglyNumber(int n)
{
// stores power of two
vector<int> power(31, 1);
for (int i = 1; i <= 30; i++)
{
power[i] = power[i - 1] * 2;
}
// initialize low and high
int l = 1, r = 2147483647;
int ans = -1;
while (l <= r)
{
int mid = l + ((r - l) / 2);
// to stores count of ugly
// numbers less than mid
int cnt = 0;
for (int i = 1; i <= mid; i *= 5)
{
for (int j = 1; j * i <= mid; j *= 3)
{
// possible powers of 3 and 5 such that
// their product is less than mid
// using the power array of 2 (pow) we are
// trying to find the max power of 2 such
// that i*j*power of 2 is less than mid
cnt += upper_bound(power.begin(), power.end(), mid / (i * j)) - power.begin();
}
}
// if count of ugly numbers less than mid
// is less than n we update l to mid + 1
if (cnt < n)
l = mid + 1;
// else update r to mid - 1
// and upate the answer
else
r = mid - 1, ans = mid;
}
return ans;
}
int main()
{
int n = 10;
cout << uglyNumber(n);
return 0;
}
// Function to get the nth ugly number
import java.util.*;
class GfG {
// Function to get the nth ugly number
static int uglyNumber(int n)
{
// stores power of two
int[] power = new int[31];
Arrays.fill(power, 1);
for (int i = 1; i <= 30; i++) {
power[i] = power[i - 1] * 2;
}
int l = 1, r = 2147483647;
int ans = -1;
while (l <= r) {
int mid = l + ((r - l) / 2);
int cnt = 0;
for (int i = 1; i <= mid; i *= 5) {
for (int j = 1; j * i <= mid; j *= 3) {
// possible powers of 3 and 5 such that
// their product is less than mid
// using the power array of 2 (power) we
// are trying to find the max power of 2
// such that i*j*power of 2 is less than
// mid
cnt += upperBound(power, mid / (i * j));
}
}
// if count of ugly numbers less than mid
// is less than n we update l to mid + 1
if (cnt < n)
l = mid + 1;
// else update r to mid - 1
// and upate the answer
else {
r = mid - 1;
ans = mid;
}
}
return ans;
}
// Helper function to find upper bound in a sorted array
static int upperBound(int[] arr, int key)
{
int low = 0, high = arr.length;
while (low < high) {
int mid = low + ((high - low) / 2);
if (arr[mid] <= key)
low = mid + 1;
else
high = mid;
}
return low;
}
public static void main(String[] args)
{
int n = 10;
System.out.println(uglyNumber(n));
}
}
# Function to get the nth ugly number
def uglyNumber(n):
# stores power of two
power = [1] * 31
for i in range(1, 31):
power[i] = power[i - 1] * 2
# initialize low and high
l = 1
r = 2147483647
ans = -1
while l <= r:
mid = l + ((r - l) // 2)
cnt = 0
i = 1
while i <= mid:
j = 1
while j * i <= mid:
# possible powers of 3 and 5 such that
# their product is less than mid
# using the power array of 2 (power) we are
# trying to find the max power of 2 such
# that i*j*power of 2 is less than mid
cnt += upperBound(power, mid // (i * j))
j *= 3
i *= 5
# if count of ugly numbers less than mid
# is less than n we update l to mid + 1
if cnt < n:
l = mid + 1
# else update r to mid - 1
# and upate the answer
else:
r = mid - 1
ans = mid
return ans
def upperBound(arr, key):
low = 0
high = len(arr)
while low < high:
mid = low + ((high - low) // 2)
if arr[mid] <= key:
low = mid + 1
else:
high = mid
return low
if __name__ == "__main__":
n = 10
print(uglyNumber(n))
// Function to get the nth ugly number
using System;
using System.Collections.Generic;
class GfG {
// Function to get the nth ugly number
static int uglyNumber(int n)
{
// stores power of two
int[] power = new int[31];
for (int i = 0; i < 31; i++) {
power[i] = 1;
}
for (int i = 1; i <= 30; i++) {
power[i] = power[i - 1] * 2;
}
int l = 1, r = 2147483647;
int ans = -1;
while (l <= r) {
int mid = l + ((r - l) / 2);
// to stores count of ugly
// numbers less than mid
int cnt = 0;
for (int i = 1; i <= mid; i *= 5) {
for (int j = 1; j * i <= mid; j *= 3) {
// possible powers of 3 and 5 such that
// their product is less than mid
// using the power array of 2 (power) we
// are trying to find the max power of 2
// such that i*j*power of 2 is less than
// mid
cnt += upperBound(power, mid / (i * j));
}
}
// if count of ugly numbers less than mid
// is less than n we update l to mid + 1
if (cnt < n)
l = mid + 1;
// else update r to mid - 1
// and upate the answer
else {
r = mid - 1;
ans = mid;
}
}
return ans;
}
// Helper function to find upper bound in a sorted array
static int upperBound(int[] arr, int key)
{
int low = 0, high = arr.Length;
while (low < high) {
int mid = low + ((high - low) / 2);
if (arr[mid] <= key)
low = mid + 1;
else
high = mid;
}
return low;
}
static void Main()
{
int n = 10;
Console.WriteLine(uglyNumber(n));
}
}
// Function to get the nth ugly number
function uglyNumber(n)
{
let power = new Array(31).fill(1);
for (let i = 1; i <= 30; i++) {
power[i] = power[i - 1] * 2;
}
// initialize low and high
let l = 1, r = 2147483647;
let ans = -1;
while (l <= r) {
// find the mid value
let mid = l + Math.floor((r - l) / 2);
// to stores count of ugly
// numbers less than mid
let cnt = 0;
for (let i = 1; i <= mid; i *= 5) {
for (let j = 1; j * i <= mid; j *= 3) {
// possible powers of 3 and 5 such that
// their product is less than mid
// using the power array of 2 (power) we are
// trying to find the max power of 2 such
// that i*j*power of 2 is less than mid
cnt += upperBound(
power, Math.floor(mid / (i * j)));
}
}
// if count of ugly numbers less than mid
// is less than n we update l to mid + 1
if (cnt < n)
l = mid + 1;
// else update r to mid - 1
// and upate the answer
else {
r = mid - 1;
ans = mid;
}
}
return ans;
}
function upperBound(arr, key)
{
let low = 0, high = arr.length;
while (low < high) {
let mid = low + Math.floor((high - low) / 2);
if (arr[mid] <= key)
low = mid + 1;
else
high = mid;
}
return low;
}
let n = 10;
console.log(uglyNumber(n));
Output
12
Time Complexity: O((log r)³), where r is the value of the Nth ugly number. Since we assume r = 21,474,836,647.
Auxiliary Space: O(1)