Write a program to find the n-th ugly number. Ugly numbers is positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, Ten is the sequence of the first ten ugly numbers. Note that 1 is typically treated as a ugly number, and N does not exceed 1690.
Test instructions: Find the nth number of ugly. n<1690.
Public class solution { public int nthuglynumber (Int n) { int[] result=new int[n]; result[0]=1; int begin=1; int m2=0,m3=0,m5=0; while (begin<n) { result[begin]= Min (result[m2]*2,result[m3]*3,result[m5]*5); // system.out.println (Result[begin]); while (Result[m2]*2<=result[begin]) { m2++; } while (Result[m3]*3<=result[begin]) { m3++; } while (Result[m5]*5<=result[begin]) { m5++; } begin++; } return result[--begin]; } Public static int min (INT&NBSP;M2,INT&NBSP;M3,INT&NBSP;M5) { int temp=m2<m3?m2:m3; return m5<temp?m5:temp; }}
PS: If you use one of the previous ugly numbers to count to Nth, the efficiency will be very low. At this point we use the ugly number behind the previous *2,*3,*5 to get the ugly number, save the previous get ugly number, there is no need to calculate all the. Efficiency improvements. idea See Sword refers to offer P183.
Leetcode264. Ugly number II Java language