The numbers that include only the mass factors 2, 3, and 5 are called ugly Numbers (Ugly number), such as 2,3,4,5,6,8,9,10,12,15, etc., and, as a rule, we treat 1 as the first ugly number.
Write an efficient algorithm that returns the nth number of ugly.
Import static Java.lang.math.min;import static Java.lang.system.out;public class Uglynumber {public static void main ( String[] args) {out.println (Findkthuglynumber (1500));} /** * Look for the K-ugly number * * @param k * @return */public static int findkthuglynumber (int k) {if (K < 0) {return 1;//return the first ugly number }int[] numbers = new Int[k];numbers[0] = 1;int Next = 1;int Ugly2index = 0;int Ugly3index = 0;int ugly5index = 0;while (NE XT < k) {int uglynum = min (numbers[ugly2index] * 2,min (Numbers[ugly3index] * 3, Numbers[ugly5index] * 5)); Numbers[next] = Uglynum;while (Numbers[ugly2index] * 2 <= Numbers[next]) {ugly2index++;} while (Numbers[ugly3index] * 3 <= Numbers[next]) {ugly3index++;} while (Numbers[ugly5index] * 5 <= Numbers[next]) {ugly5index++;} next++;} Return numbers[k-1];//start from 0}}
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
First Look at K, an ugly number.