数値の整数次数(Java実装)

12383 ワード


public class E16Power {
    // 
    // 、 、 

    // 
    public static double power_solution1(double base, int exponent){
        // 
        if (base == 0.0 && exponent < 0)
            throw new IllegalArgumentException("Illegal Input!");
        if (exponent == 0)
            return 1.0;
        // exponent 
        double result = nonnegativePower1(base, Math.abs(exponent));
        if (exponent < 0)
            return 1.0 / result;
        else
            return result;
    }

    private static double nonnegativePower1(double base, int exponent){
        //exponent > 0
        double result = 1.0;
        int step = 0;
        while(step <= exponent){
            result *= base;
            step++;
        }
        return result;
    }

    // 
    public static double power_solution2(double base, int exponent){
        if (base == 0.0 && exponent < 0)
            throw new IllegalArgumentException("Illegal Input!");
        double result = nonnegativePower2(base, Math.abs(exponent));
        if (exponent < 0)
            return 1.0 / result;
        else
            return result;
    }

    private static double nonnegativePower2(double base, int exponent){
        //exponent > 0
        // 
        if (exponent == 0)
            return 1.0;
        if(exponent == 1)
            return base;

        double result = power_solution2(base, exponent >> 1);
        result *= result;
        // 1 
        if ((exponent & 0x1) == 1)
            result *= base;
        return result;
    }

    public static void main(String[] args){
        System.out.println(E16Power.power_solution2(2.5, 3));
        System.out.println(E16Power.power_solution2(2.5, -3));
        System.out.println(E16Power.power_solution2(2.5, 0));
        System.out.println(E16Power.power_solution2(0, 1));
        System.out.println(E16Power.power_solution2(0, 0));
        //System.out.println(E16Power.power_solution2(0, -1)); //IllegalArgumentException
    }
}