-
Notifications
You must be signed in to change notification settings - Fork 49
/
Ugly Numbers
54 lines (44 loc) · 830 Bytes
/
Ugly Numbers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 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;
}
// This code is contributed by shivanisinghss2110