# Algorithm: x's n-th square

Source: Internet
Author: User

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

Related Keywords:

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.