简体   繁体   中英

How to raise a BigInteger to the power of something without pow()

My Java Professor wants me to write a program where the user gives a value for x and a value for y, and then computes the value of x^y (x to the power of y), and prints it to the console. I'm not allowed to use the pow() method for this. x and y are int values.

My code, after the user gives x and y values:

BigInteger solution = BigInteger.valueOf(0);
    for (int i=0; i<y; i++) {
        solution = solution.add(BigInteger.valueOf((x+solution.intValue())*x));
    }

But it never works properly. The answer it gives is usually waaaay off. If anyone has code that would correct this problem, your assistance would be much appreciated!

You just need to multiply x by itself y times.

BigInteger solution;

if (y == 0) {
    solution = BigInteger.valueOf(1);
}
else if (y > 0) {        
    solution = BigInteger.valueOf(x);
    for (int i=0; i<y-1; i++) {
        solution = solution.multiply(BigInteger.valueOf(x));
    }
}
else {
    // Negative powers left as exercise to the reader
}

You can do something like this:

public void function(int x, int y){

    BigInteger sol = BigInteger.ONE;

            for (int i = 0; i < x; i++) {

                sol = sol.multiply(BigInteger.valueOf(y));

            }

            System.out.println(sol);

    }

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