This class will allow you to produce a^n for all real n
class Power { void run() { System.out.println("Program to compute a number a to the power of b\nTrial Values will be 5^0, 5^1 and 5^2, 5^3\nEnjoy\n\n"); //series of test values //Values are of type double, hence for Elements format to 0 decimal places System.out.println("(5,0) = " + String.format("%.0f",determinePower(5,0)) ); System.out.println("(5,1) = " + String.format("%.0f",determinePower(5,1)) ); System.out.println("(5,2) = " + String.format("%.0f",determinePower(5,2)) ); System.out.println("(5,3) = " + String.format("%.0f",determinePower(5,3)) ); System.out.println(); //for negative bases and powers set decimal places longer i.e "%.4f" for four places System.out.println("(5,-1) = " + String.format("%.4f",determinePower(5,-1)) ); System.out.println("(5,-3) = " + String.format("%.4f",determinePower(5,-3)) ); System.out.println("(-1,1) = " + String.format("%.4f",determinePower(-1,1)) ); System.out.println("(-2,2) = " + String.format("%.4f",determinePower(-2,2)) ); System.out.println("(-2,3) = " + String.format("%.4f",determinePower(-2,3)) ); System.out.println("(-1,0) = " + String.format("%.4f",determinePower(-1,0)) ); System.out.println(); System.out.println("(-2,-2) = " + String.format("%.4f",determinePower(-2,-2)) ); } // Function to Determine the power of a base and power double determinePower(double base, double power) { double answer = 1; // Any base to power of zero == 1 if (power == 0) return 1; // Any base to the power of one is equal to the base else if (power == 1) return base; // Iterative loop to compute all other values. Assuming // values >= 0 else if (power > 1) { for(int i = 1; i <= power; i++) { answer *= base; } return answer; } else if (power == -1) { return 1 / base; } //handle negative powers else if (power < 0) { double absolutePower = -power; // make power a positive value // for the sake of iteration. // can be left negative - for loop // would need modification for (int k = 0; k < absolutePower; k++) { answer *= base; } return (1 / answer); } else return -1; } public static void main(String[] args) { Power myPower = new Power(); myPower.run(); } }
