Java tutorial
//package com.java2s; /* * Copyright 2013 Valentyn Kolesnikov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.math.BigDecimal; public class Main { /** * Compute x^exponent to a given scale. Uses the same algorithm as class * numbercruncher.mathutils.IntPower. * * @param x * the value x * @param exponent * the exponent value * @param scale * the desired scale of the result * @return the result value */ public static BigDecimal intPower(BigDecimal x, long exponent, int scale) { // If the exponent is negative, compute 1/(x^-exponent). if (exponent < 0) { return BigDecimal.valueOf(1).divide(intPower(x, -exponent, scale), scale, BigDecimal.ROUND_HALF_EVEN); } BigDecimal power = BigDecimal.valueOf(1); // Loop to compute value^exponent. while (exponent > 0) { // Is the rightmost bit a 1? if ((exponent & 1) == 1) { power = power.multiply(x).setScale(scale, BigDecimal.ROUND_HALF_EVEN); } // Square x and shift exponent 1 bit to the right. x = x.multiply(x).setScale(scale, BigDecimal.ROUND_HALF_EVEN); exponent >>= 1; Thread.yield(); } return power; } }