Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions UglyNumbers.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// C++ program to find nth ugly number
#include <iostream>
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 no)
{
no = maxDivide(no, 2);
no = maxDivide(no, 3);
no = maxDivide(no, 5);

return (no == 1) ? 1 : 0;
}

// Function to get the nth ugly number
int getNthUglyNo(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;
}

// Driver Code
int main()
{

// Function call
unsigned no = getNthUglyNo(150);
cout << "150th ugly no. is " << no;
return 0;
}