Looking for the nth number of ugly

Source: Internet
Author: User

The numbers that contain only the mass factors 2, 3, and 5 are called ugly Numbers (Ugly number), for example: 2,3,4,5,6,8,9,10,12,15, etc., we used to 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];//starting from 0}}



Looking for the nth number of ugly

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.