From 7a4b8258953c6f92c1c7c29c3e13fe991f3e214e Mon Sep 17 00:00:00 2001 From: Namisha Goyal <44649227+namigoel@users.noreply.github.com> Date: Mon, 31 Oct 2022 22:46:44 +0530 Subject: [PATCH] Create UglyNumbers.cpp --- UglyNumbers.cpp | 52 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 UglyNumbers.cpp diff --git a/UglyNumbers.cpp b/UglyNumbers.cpp new file mode 100644 index 0000000..b0763ac --- /dev/null +++ b/UglyNumbers.cpp @@ -0,0 +1,52 @@ +// C++ program to find nth ugly number +#include +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; +}