The number of K factorization can only be calculated for 3,5,7

Source: Internet
Author: User

English Description: Design an algorithm to find the kth number such, the only prime factors is 3, 5, and 7


Idea: Factorization can only be 3,5,7, set this number to Val, then val = (3^i) (5^j) (7^n) (i,j,n>=0), obviously the 1th number is 1, 2nd is 1*3, 3rd is 1*5, 4th is 1*7, 5th is 3*3, 6th is a 5, the 7th one for 3*7 ...

If the number of money k-1 into a linked list R, it can be seen that the number of K is 3 or 5 or 7 times the number of previous k-1 one, to get a minimum number of R has not been added. To prevent too many loops, we should keep a record of this smallest number.

Code:

1#include <queue>2 3 intFindNum (intk)4 {5     if(k <=0)6         return 0;7     intval =1;8queue<int> Q3; Q3.push (3);9queue<int> Q5; Q5.push (5);Tenqueue<int> Q7; Q7.push (7); One  A      for(k--; k >0; k--) -     { -val =findmin (Q3.front (), Q5.front (), Q7.front ()); the         if(val = =Q7.front ()) - Q7.pop (); -         Else -         { +             if(val = =Q5.front ()) - Q5.pop (); +             Else A             { at Q3.pop (); -Q3.push (Val *3); -             } -Q5.push (Val *5); -         } -Q7.push (val*7); in     } -  to     returnVal; + } - intFindmin (intAintBintc) the { *     intresult =0; $     if(A <b)Panax Notoginsengresult =A; -     Elseresult =b; the     if(Result >c) +result =C; A     returnresult; the}

I used the C + + STL template Queue (queues, first in, first out), Q3,q5,q7 to record the last minimum number multiplied by the 3,5,7 result for later use. The smallest number once used, immediately out of the team.

The number of K factorization can only be calculated for 3,5,7

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.