Topic description:
Returns the value of the first argument raised to the power of the second argument. |
The simple way to calculate A^n is to loop n times to exponentiate, so as to get the O(n) time complexity method. In fact, everyone wants to get an optimized method, that is, A^n=A^(n/2) *A^(n/2), keep recursing, during which you can omit a lot of unnecessary calculations, and get the method of O(logn).
The following is a description of a fast exponentiation operation using the binary method.
We use binary instead of power n, for example, the binary of 10 is 1010 (binary is believed to be everyone)
Here the 1st and 3rd bits (reverse numbers) are 1, so we ask for A^10 and convert it to A^10=A^(2^3)*A^(2^1); what is the benefit of doing this? Woolen cloth?
We know that for 10 (1010), each binary bit corresponds to several powers of A? They are A^1 A^2 A^4 A^8 (also starting from the low position); note the relationship between the powers before and after here: A^(n) = A^(n-1)*A^(n- 1) (where n represents the number of binary digits) Isn't it? For example, A^8=A^4*A^4, A^4=A^2*A^2....
The code is represented as:
while(n) { if(n&1) //Indicates that the last bit is 1, because we can judge which bits in the binary bits of n are 1 by shifting { ans *= A;//ans represents the final result } A = A*A; //Pay attention to the relationship between the several powers of A corresponding to the front and rear binary bits mentioned above (while shifting, calculate which bit represents the several powers of A) n>>1; }Then the code for this question:
import java.util.Scanner; /* * Given a float base of type double and an integer exponent of type int. Find the exponent power of base. */ public class Power { public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()){ double base = in.nextDouble(); int exponent1 = in.nextInt(); double result = power(base, exponent1); System.out.println(result); } } public static double power(double base, int exponent1) { double res = 1,curr = base; int exponent; if(exponent1>0){ exponent = exponent1; }else if(exponent1<0){ if(base==0) throw new RuntimeException("The denominator cannot be 0"); exponent = -exponent1; }else{// exponent1 is 0 return 1;// any number raised to the power of 0 } while(exponent!=0){ if((exponent&1)==1) res*=curr; curr*=curr; // double exponent>>=1;//Shift right one place } return exponent1>=0?res:(1/res); } }