next up previous index
Next: Index Up: Answers to Assignment 2 Previous: Subroutine factor_nodes

Subroutine minpower2

This subroutine finds a smallest integer that is a power of 2 and that is greater than or equal to its first argument. The power itself is then returned in the second argument and the integer is returned as the value of the function.

The subroutine goes about its business by dividing the first argument by 2 until nothing is left. The highest loop index, i, attained while executing the loop, is then used as an exponens. There is a small subtlety here: if the first argument is a power of 2 then the exponens is actually i-1, and the number returned is the same as the first argument. Otherwise the exponens is i and the value returned by minpower2 is 2i.

Observe the   use of EXIT   and label powerloop. The effect is similar to aborting a loop with a goto in C-language programs.

The function also checks   for an overflow on 2i, but doesn't do anything exciting about it other than writing a message on standard output, which is a rather bad idea, because a program that calls it may end up evaluating some nonsense. In this program this doesn't matter, because you're unlikely to work with a machine that has more than 231 processors any time soon.


next up previous index
Next: Index Up: Answers to Assignment 2 Previous: Subroutine factor_nodes
Zdzislaw Meglicki
2001-02-26