= Solution
Print separators before all but the first term, so there is neither a leading nor a trailing plus sign:
``
def printRat(num: Int, den: Int): Unit = {
print(num.toString + "/" + den.toString)
}
def printEgypt(e: Array[Int]): Unit = {
if (e.isEmpty) print("0")
var i = 0
while (i < e.length) {
if (i > 0) print(" + ")
print("1/" + e(i).toString)
i += 1
}
}
``
The <loop invariant> says that exactly the first $i$ <unit fractions> have been printed in order, separated by ` + `, with no trailing separator. The <loop variant> is $e.length-i$. The empty <array> is displayed as zero. Since $5/7-1/2=3/14$ and $3/14-1/5=1/70$, \b[the output is `5/7 = 1/2 + 1/5 + 1/70`]. The source's earlier example with middle denominator $4$ and final denominator $70$ contains the arithmetic typo; its final printing example is correct. Indeed $1/2+1/4>5/7$, so no positive final term could repair that particular prefix. The printing routine reports the generated terms rather than imposing a particular expansion.
Back to article page