Question: only the number of factors 2, 3 and 5 is an ugly number.
1,500th ugly numbers from small to large
We usually regard 1 as the first ugly number.
Method 1: judge whether each integer is an ugly number one by one
How can we determine whether a number is ugly? According to the definition, the ugly number can only be divided by 2, 3, 5, that is, the factor of this number can only be 2, 3, 5
We continue to divide this number by 2, 3, 5 until the end, if we get 1, this number is ugly.
bool IsUgly(int num){ assert(num >= 0); while (num % 2 == 0) { num /= 2; } while (num % 3 == 0) { num /= 3; } while (num % 5 == 0) { num /= 5; } return (num == 1) ? true : false;}
Next, you only need to judge in order whether each integer is an ugly number.
Method 2:
The previous method is inefficient because it needs to judge whether each number is an ugly number. It takes a lot of time for a non-ugly number.
According to the definition of the ugly number, the factors of the ugly number can only be 2, 3, 5. We can know that the result of dividing the big ugly number by the number of more clown numbers can only be the product of 2, 3, and 5, that is, the division result is also an ugly number.
We can create an array where the numbers are the ugly numbers in the sorted order. Each ugly number in it is obtained by multiplying the ugly number in front by 2, 3, or 5.
The key to this idea is how to ensure that the ugly numbers in the array are sorted in order.
Given the first K ugly numbers (U1, U2, U3 ,..., UK), calculate the k + 1 ugly number UK + 1
The number k + 1 ugly number must be one of the first K ugly numbers multiplied2,3,5A result,
Of the first K ugly numbersFind the smallest ugly numberp2,p3,p5, Makingp2*2>Uk;p3*3>Uk;p5*5>Uk, AfterUk+1=min(p2*2, p3*3, p5*5)
Note: because the current ugly numbers are sorted in good order, the next search for P2, P3, and P5 does not need to start from the beginning. You only need to start from the previous P2, P3, P5.
long long KthUgly(int kth) { assert(kth >= 1); std::vector<long long> ugly(kth, 0); int index2 = 0; int index3 = 0; int index5 = 0; ugly.at(0) = 1; int lastIndex = 0; while (lastIndex + 1 != kth) { while (ugly.at(index2) * 2 <= ugly.at(lastIndex)) { ++index2; } while (ugly.at(index3) * 3 <= ugly.at(lastIndex)) { ++index3; } while (ugly.at(index5) * 5 <= ugly.at(lastIndex)) { ++index5; } long long min = std::min(std::min(ugly.at(index2) * 2, ugly.at(index3) * 3), ugly.at(index5) * 5); ++lastIndex; ugly.at(lastIndex) = min; } return ugly.at(lastIndex);}