The problem is for the company to teach, and no difficulty. Used to illustrate the efficiency differences between algorithms and loops and recursion.
Packagepractice;ImportJava.math.BigDecimal;/** * @authorCaiyu * @date 2014-12-3*/ Public classX_n_square {StaticBigDecimal x =NewBigDecimal (7); Public Static voidMain (string[] args) {intn = 100000; BigDecimal result=x; LongTime =System.currenttimemillis (); if(N < 5000) for(inti = 1; I < n; i++) {result=result.multiply (x); } System.out.println (System.currenttimemillis ()-Time ); if(N < 5000) System.out.println (result); time=System.currenttimemillis (); Result=cal (n, x); System.out.println (System.currenttimemillis ()-Time ); if(N < 5000) System.out.println (result); time=System.currenttimemillis (); //change the bottom formula intCount = (int) Math.floor (Math.log (n)/Math.log (2)); Result=x; while(true) { if(count--= = 0) Break; Result= (n >> count)% 2 = = 0?result.multiply (Result): result. Multiply (result). multiply (x); } System.out.println (System.currenttimemillis ()-Time ); if(N < 5000) System.out.println (result); } Public StaticBigDecimal Cal (intN, BigDecimal R) { if(n = = 1) returnx; if(n% 2 = = 0) {R= Cal (N/2, R); returnr.multiply (R); } Else{R= Cal ((n-1)/2, R); returnr.multiply (R). multiply (x); } }}
Algorithm: x's n-th square