From d9a49e1f1ebc0689d3bd17412a35bd1a2bf1e5f2 Mon Sep 17 00:00:00 2001 From: deepak7336 <70963318+deepak7336@users.noreply.github.com> Date: Sat, 1 Oct 2022 00:54:44 +0530 Subject: [PATCH] Create ugly_numbers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention, 1 is included. Given a number n, the task is to find n’th Ugly number. --- C++/ugly_numbers | 53 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 C++/ugly_numbers diff --git a/C++/ugly_numbers b/C++/ugly_numbers new file mode 100644 index 0000000..446fc9b --- /dev/null +++ b/C++/ugly_numbers @@ -0,0 +1,53 @@ +// 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; +} +