// FILE: PowerDemo.java // This program illustrates the use of the power and pow method that uses // recursion to calculate the value of a number raised to an integer power. import java.io.IOException; import edu.colorado.io.EasyReader ; /****************************************************************************** * The PowerDemo Java application illustrates the use of * the power and pow methods, which use recursion to * calculate the value of a number raised to an integer power. * *

Java Source Code for this class: * * http://www.cs.colorado.edu/~main/applications/PowerDemo.java * * * @author Michael Main * (main@colorado.edu) * * @version Feb 10, 2016 ******************************************************************************/ public class PowerDemo { /** * The main method activates power and * pow with parameters that are provided by the user. * @param args * not used in this implementations **/ public static void main(String[ ] args) { EasyReader stdin = new EasyReader(System.in); int n; double x; System.out.println ("I can calculate the value of x raised to an integer power."); do { x = stdin.doubleQuery("The value of x: "); n = stdin.intQuery("The integer power: "); System.out.println("Answer using the power method: " + power(x,n)); System.out.println("Answer using the pow method: " + pow(x,n)); } while (stdin.query("Do you want to try other values?")); System.out.println("Thank you beary much."); } /** * Computes the value of x raised to the n power. * @param x * any double number * @param n * the int power to raise x to * Precondition: * If x is zero, then n must be positive. * @return * x raised to the n power * @exception java.lang.IllegalArgumentException * Indicates that x is zero and n is not positive. **/ public static double power(double x, int n) { double product; // The product of x with itself n times int count; if (x == 0 && n <= 0) throw new IllegalArgumentException("x is zero and n=" + n); if (n >= 0) { product = 1; for (count = 1; count <= n; count++) product = product * x; return product; } else return 1/power(x, -n); } /** * Alternate implementation of the power method. * @param x * base * @param n * exponent * @return * x to the n power **/ public static double pow(double x, int n) { if (x == 0 && n <= 0) throw new IllegalArgumentException("x is zero and n=" + n); else if (n == 0) return 1; else if (n > 0) return x * pow(x, n-1); else // x is nonzero, and n is negative. return 1/pow(x, -n); } }