简体   繁体   中英

About a method for an integer to nth power using BigInteger to calculate big numbers

Question from the book: Many encryption techniques depend on the ability to raise large integers to an integer power. Here is a method that implements a (reasonably) fast technique for integer exponentiation:

public static int pow(int x, int n) { 
    if (n == 0){
        return 1;
    }
    int t = pow(x, n/2);
    // find x to the n/2 recursively
    // if n is even, the result is t squared 
    // if n is odd, the result is t squared times x
    if (n%2 == 0){ 
        return t*t; 
    } else { 
        return t*t*x; 
    }
} 

The problem with this method is that it only works if the result is smaller than 2 billion. Rewrite it so that the result is a BigInteger. The parameters should still be integers, though.

You can use the BigInteger methods add and multiply, but don't use pow , which would spoil the fun.

Well the method, I didn't really care how it works, but the "arrowed" part is the one that I'm confused about. It says "don't use pow ." What does that mean? They give you the method and tells you to implement BigInteger , but what does it mean by "don't use pow?" Does anyone know?

In a java.math.BigInteger Object there is a method pow.The

java.math.BigInteger pow(int)

Using this method you can calculate the the power of any number.

In your example we could use BigInteger to write the function as

import java.math.BigInteger;
public static BigInteger power(int a,int b){
BigInteger b1 = new BigInteger(Integer.toString());
b1 = b1.pow(b);
return b1;//returns a^b
}

Now using pow is built in function. I think that the statement means that you are expected to provide an alternate implementation of the process using different approach such as

import java.math.BigInteger;
public static BigInteger power(int a,int b){
BigInteger b1 = new BigInteger(Integer.toString(a));  
BigInteger b2 = new BigInteger("1");
for(int i = 0; i < b; i++){
b2=b2.multiply(b1);
}
return b2;//return a^b
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM