package username.analysis; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Random; import java.util.Vector; /** * A class that supports various kinds of mathematical computations. * * @author Samuel A. Rebelsky * @version 1.0 of April 2006 */ public class Mathematician { // +--------+-------------------------------------------------- // | Fields | // +--------+ /** The analyst that helps determine running time. */ Analyst a; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ /** * Build a new searcher that records information using * an analyst. */ public Mathematician(Analyst _a) { this.a = _a; } // Mathematician(Analyst) // +-----------------+----------------------------------------- // | Primary Methods | // +-----------------+ /** * Compute x^n using a straightforward for loop. * * @pre * n >= 0 * @post * result = x * x * x * ... * x, with n x's. */ public BigDecimal exptFor(BigDecimal x, int n) { BigDecimal result = new BigDecimal(1.0); for (int i = 0; i < n ; i++) { a.step(); result = result.multiply(x); } return result; } // exptFor(BigDecimal, int) /** * Compute x^n using a clever algorithm. * * @pre * n >= 0 * @post * result = x * x * x * ... * x, with n x's. */ public BigDecimal exptWhile(BigDecimal x, int n) { BigDecimal accumulator = new BigDecimal(1); // need to repeatedly reduce the power. Idea: // currentx^currentn * accumulator = originalx^originaln while (n > 0) { a.step(); // If n is even, divide it by two and multiply x by // itself, using the amazing rule that // (x^n = (x^2)^(n/2)) if ((n % 2) == 0) { n = n/2; x = x.multiply(x); } // n is even // If n is odd, subtract 1 from it and .. else { n = n - 1; accumulator = x.multiply(accumulator); } // n is odd } // while return accumulator; } // exptWhile(BigDecimal, int) } // class Mathematician