Nine-chapter algorithm surface question 64 Find the special number of k large

Source: Internet
Author: User

Nine Chapters count judges Net-original website

http://www.jiuzhang.com/problem/65/


Topics

There is a special number, its prime factor is only possible 3,5,7, it can not be the other prime, we put this number from small to large sort, get 3, 5, 7, 9, 15 ... Now we are asking for the number of K, for example, the 4th largest is 9.


Online test

http://lintcode.com/en/problem/kth-prime-number/


Answer

The elements we require are divided into three classes of elements if divided by 3,5,7 and then sorted.

A. 1x3, 3x3, 5x3, 7x3,9x3, ...

B. 1x5, 3x5, 5x5, 7x5, 9x5, ...

C. 1x7, 3x7, 5x7, 7x7, 9x7,...

In fact, the equivalent is to merge three columns together, and then find out the number of the merge sequence K, and the decomposition of the two numbers multiplied by the first element is exactly what we asked for, then the second number is 3,5,7. We know that the merge three sequence algorithm uses three pointers, so we can learn from this merge approach. We set three pointers to P3,P5,P7, starting with the p3=0,p5=0,p7=0, and then using an array A to record the sequence we requested. At the beginning of the sequence the first element is a[0]=1, and then each time the smallest element in the selection (A[p3]*3,a[p5]*5, a[p7]*7) is inserted into array A as the next element, if the smallest element is P3, then P3 refers to the next element p3++, similarly if P5, p5++, If it is P7 so p7++, then step K, A[k] will store the elements we ask for. So the time complexity of the last question is O (n).


Nine-chapter algorithm surface question 64 Find the special number of k large

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.