Discrete Mathematics and Its Applications, Seventh Edition

Published by McGraw-Hill Education
ISBN 10: 0073383090
ISBN 13: 978-0-07338-309-5

Chapter 3 - Section 3.1 - Algorithms - Exercises - Page 202: 10

Answer

procedure pow ($x$ a real number, $n$ an integer) if $n>0$ then return positivepow($x, n$) else if $x$ is $0$ then return undefined else return 1/positivepow($x, -n$). procedure positivepow($x$ a real number, $n$ a positive integer) if $x$ is $0$ then return $0$ else product:=1 for $i:=1$ to $n$ $\space\space\space$product:= product $\times x$ return product

Work Step by Step

The aim of this exercise is to derive an algorithm that, when given $x$ and $n$, can calculate $x^n$. Edge cases must be handled carefully such as the the case where $x=0$ to make sure the algorithm is robust. First, as suggested in the question, we define a positivepow procedure which assumes that the power is positive and works accordingly. Notice that when $n=0$, our algorithm handles that case properly as well since it returns $1$ (because the loop never executes as the condition is false from the very beginning) For the negative power, we extend the positivepow procedure making use of the relation $x^{-n}=\frac{1}{x^n}$. For $x=0,$ the algorithm should return $1$ for $n>0$; undefined otherwise which what the above algorithm does.
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.