"Sword means offer" ugly number

Source: Internet
Author: User

Problem description

The numbers that contain only the factors 2, 3, and 5 are called ugly Numbers (Ugly number). For example, 6, 8 are ugly numbers, but 14 is not, because it contains factor 7. We used to think of 1 as the first ugly number. Find the nth ugly number in order from small to large.

Algorithm analysis

The number of ugly numbers in each location is the result of an ugly multiply by 2 or 3 or 5, see the following example:

The 1th ugly number is 1,
The 2nd ugly number is 1 * 2 = 2, 1th ugly number
The 3rd ugly number is 1 * 3 = 3, 1th ugly number
The 4th ugly number is 2 * 2 = 4, 2nd ugly number
The 5th ugly number is 1 * 5 = 5, the 1th ugly number is a
The 6th ugly number is 2 * 3 = 6, 2nd ugly number
。。。。。
We recorded the position of 2, 3, 5 in W2,W3,W5 respectively, the initial 0, the number of ugly sequence is a
In the beginning, we had only 1 ugly numbers,
The 2nd ugly number is min (a[w2]*2, a[w3]*3, a[w5]*5), then the minimum value is a[w2]*2, so W2 can move backwards one, so the next time is to calculate the 2nd ugly number multiplied by 2,
This ensures that the number of ugly sequences continues to increase until the index number is found.

 class solution { Public:intGetuglynumber_solution (int Index) {if(Index==1)return 1;int* x =New int[Index]; x[0] =1;intW2 =0, W3 =0, W5 =0; for(inti =1, j =1; I <Index; i++) {intTMP2 = x[w2] *2;intTmp3 = x[w3] *3;intTMP5 = x[w5] *5;intt = min (tmp2, min (Tmp3, TMP5));if(t = = tmp2) w2++;if(t = = Tmp3) w3++;if(t = = tmp5) w5++;        X[i] = t; }returnx[Index-1]; }};

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Sword means offer" ugly number

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.