package rebelsky.computation; import java.math.BigDecimal; /** * More fun computations! * * @author Samuel A. Rebelsky * @version 1.0 of October 2004 */ public class Computer { // +--------+-------------------------------------------------- // | Fields | // +--------+ /** * The number of "steps" done in the recent computation. */ long steps; // +---------------------+------------------------------------- // | Bookkeeping Methods | // +---------------------+ /** * Reset the number of steps taken to 0. */ public void reset() { this.steps = 0; } // reset() /** * Get a count of the number of steps since the last * call to reset. */ public long steps() { return this.steps; } // steps() // +---------------------+------------------------------------- // | Computation Methods | // +---------------------+ /** * Compute x^y iteratively. */ public BigDecimal expi(BigDecimal x, long y) { BigDecimal result = new BigDecimal(1.0); for (long i = 0; i < y; i++) { result = result.multiply(x); ++this.steps; } return result; } // expi(BigDecimal, long) /** * Compute x^y using clever recursion. */ public BigDecimal expr(BigDecimal x, long y) { if (y == 0) return new BigDecimal(1.0); else if (2* (y / 2) != y) { // y is odd ++this.steps; return x.multiply(expr(x, y-1)); } else { BigDecimal tmp = expr(x, y/2); ++this.steps; return tmp.multiply(tmp); } } // expr(BigDecimal, long) } // class Computer