Here you can find the source of power(final BigDecimal value, final long power)
This method returns the value multiplied by itself a number of times equal to the power.
Internally, it uses bit-shifting and recursion to only perform 2 * ceil(lg(value))
or less multiplications.
Parameter | Description |
---|---|
value | the value to multiply by itself |
power | the number of times to multiply the value |
public static BigDecimal power(final BigDecimal value, final long power)
//package com.java2s; /*//from www . j a va2 s .com * Copyright (C) 2015 Wesley Wolfe * Works provided with supplemented terms, outlined in accompanying * documentation, or found at https://github.com/Wolvereness/UHCL-ScholWork * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.math.BigDecimal; public class Main { /** * <p>This method returns the value multiplied by itself a number of times * equal to the power.</p> * <p>Internally, it uses bit-shifting and recursion to only perform * <code>2 * ceil(lg(value))</code>or less multiplications.</p> * * @param value the value to multiply by itself * @param power the number of times to multiply the value * @return the resulting number */ public static BigDecimal power(final BigDecimal value, final long power) { // anything to zero is just 1 if (power == 0) { return BigDecimal.ONE; } // the 'lowerValue' is our value raised to power / 2. BigDecimal lowerValue = power(value, power >>> 1); // since it was only raised to the power / 2, we need to square it to compensate for current power // Consider: // (value^(power/2))^2 == // (value^(power/2)) * (value^(power/2)) == // (value^(power/2 + power/2)) == // value^power lowerValue = lowerValue.multiply(lowerValue); if ((power & 0x1l) == 0x1l) { // This means that the exponent is odd // Or, to rephrase, power == floor(power/2) + 1 // Thus, value^power == value * (value^(floor(power/2)))^2 return lowerValue.multiply(value); } else { // This means that the exponent is even // Or, to rephrase, power == floor(power/2) return lowerValue; } } }