The numbers that contain only 2, 3, and 5 are called ugly Numbers (Ugly number), for example: 2,3,4,5,6,8,9,10,12,15, and so on, we used to think of 1 as the first ugly number.
Write an efficient algorithm to return the nth ugly number.
Solution 1: To determine whether a number is an ugly number, consecutive find the nth number of ugly
#include <iostream>
using namespace std;
BOOL isugly (int num) {
if (num < 1) return
false;
if (num = 1) return
true;
while (num% 2 = 0)
num/= 2;
while (num% 3 = 0)
num/= 3;
while (num% 5 = 0)
num/= 5;
return num = = 1;
}
int nthugly (int n) {
int index = 1, x = 2;
while (Index < n) {
if (isugly (x)) {
index++;
++x;
}
else
++x;
}
return x-1;
}
int main () {
int n;
cout << "Input the number n:\n";
CIN >> N;
cout << nthugly (n);
return 0;
}
Solution 2: Multiply 2,3,5 in the current ugly number to find the smallest subsequent ugly number added to the sequence
#include <iostream>
using namespace std;
int minOf3 (int a, int b, int c) {
int temp = (A < b a:b);
Return (Temp < C. temp:c);
}
Long findugly (int n) {
int *ugly = new Int[n];
Ugly[0] = 1;
int index2 = 0, index3 = 0, index5 = 0;
int index = 1;
while (Index < n) {
int val = minOf3 (Ugly[index2] * 2, UGLY[INDEX3] * 3, UGLY[INDEX5] * 5);
Ugly[index] = val;
while (Val >= ugly[index2] * 2)
++index2;
while (Val >= ugly[index3] * 3)
++index3;
while (Val >= ugly[index5] * 5)
++index5;
index++;
}
cout << ugly[n-1];
delete [] ugly;
return 0;
}
int main () {
int n;
cout << "Input the number n:\n";
CIN >> N;
findugly (n);
return 0;
}