/**
* Function: Some number of prime factor only 3, 5, 7, find the number of K.
*/
Two methods:
Method One:
/** * Idea: Multiply the numbers in the list with 3,5,7 to find the decimal places that are not yet added to the list. * Each time AI is added to the list, a temporary list is used to store 3ai,5ai and 7Ai. To generate ai+1, search the temporary list to find the minimum value. * @param k * @return */public static int getkthmagicnumger (int k) {if (k<0) return 0;int val=1; Queue q=new linkedlist<integer> (); addproducts (q,1); for (int i=0;i<k;i++) {val=removemin (q); Addproducts (q, val);} return Val;} public static void Addproducts (Queue<integer> q,int v) {q.add (v*3); Q.add (v*5); Q.add (v*7);} Remove minimum public static int removemin (queue<integer> q) {int min=q.peek (), for (Integer v:q) {if (v<min) {min=v;}} while (Q.contains (min)) {q.remove (min);} return min;}
Method Two:
/** * Idea: (optimized) to group the list by a constant factor from the start, just check the first of 3, 5, and 7 times times, and the subsequent elements must be larger than the first one. * When these elements do not exist in the other list, insert them into the list. * Pseudo code as follows: * 1) Initialize array and queue: Q3,q5 and Q7. * 2) Insert 1 into the array. * 3) Insert the 1*3,1*5,1*7 into Q3,q5 and Q7, respectively. * 4) make x the minimum value in Q3,q5 and Q7. Adds x to the end of the array. * 5) If x exists: * Q3: Put x*3,x*5,x*7 in Q3,q5 and Q7, remove X from Q3. * Q5: X*5,x*7 into Q5 and Q7, remove X from Q5. * Q7: X*7 is placed in Q7, and X is removed from Q7. * 6) Repeat 4~6 until the k element is found. * @param k * @return */public static int getKthMagitNumber2 (int k) {if (k<0) return 0;int val=1; Queue<integer> queue3=new linkedlist<integer> (); Queue<integer> queue5=new linkedlist<integer> (); Queue<integer> queue7=new linkedlist<integer> () queue3.add (1); for (int i=0;i<k;i++) {int v3= Queue3.size () >0?queue3.peek (): Integer. Max_value;int v5=queue5.size () >0?queue5.peek (): Integer. Max_value;int v7=queue7.size () >0?queue7.peek (): Integer. Max_value;val=math.min (v3, Math.min (V5, V7)), if (val==v3) {queue3.remove (); Queue3.add (val*3); Queue5.add (val*5);} else if (val==v7) {queue5.remove (); Queue5.add (val*5);} else if (val==v7) {queue7.remove ();}queue7.add (val*7);} return Val;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
9.7 Mathematics and Probability (v)-function: Some number of prime factor only 3, 5, 7, find out the number of K