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