Java Number Power power(int base, int power)

Here you can find the source of power(int base, int power)

Description

Returns the integer result of base^power

License

Open Source License

Parameter

Parameter Description
base base integer of the operation
power power that base is raised to

Return

base raised to exponent power (rounded by integer operations)

Declaration

public static int power(int base, int power) 

Method Source Code

//package com.java2s;
/*/* w  ww.  j a va2 s  .  com*/
 *  Java Information Dynamics Toolkit (JIDT)
 *  Copyright (C) 2012, Joseph T. Lizier
 *  
 *  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/>.
 */

public class Main {
    /**
     * Returns the integer result of base^power
     * 
     * @param base base integer of the operation
     * @param power power that base is raised to
     * @return base raised to exponent power (rounded by integer operations)
     */
    public static int power(int base, int power) {
        int result = 1;
        int absPower = Math.abs(power);
        for (int p = 0; p < absPower; p++) {
            result *= base;
        }
        if (power < 0) {
            // This will be zero for any base except 1 or -1
            result = 1 / result;
        }
        return result;
    }

    /**
     * Returns the integer result of base^power
     * 
     * Tested - works.
     * 
     * @param base
     * @param power
     * @return
     */
    public static long power(long base, long power) {
        long result = 1;
        long absPower = Math.abs(power);
        for (long p = 0; p < absPower; p++) {
            result *= base;
        }
        if (power < 0) {
            // This will be zero for any base except 1 or -1
            result = 1 / result;
        }
        return result;
    }
}

Related

  1. pow4(double val)
  2. pow9(final double x)
  3. powDecay(double x, double y)
  4. power(double d, int exp)
  5. power(final long x, final long n, final long p)
  6. power(int i)
  7. power(int val, int numOfPower)
  8. power(int x, int n)
  9. power(long x, long y)