Friday, 2 November 2007

How many Java programmers does it take to round up to a power of 2?

Came across this thread through the news.yc RSS feed. Found it quite interesting for many reasons. Now I know I haven't handled negative values, but here is what I did in Python:


def roundup_pow2f(a):
if a <= 0: raise RuntimeError, "Oops. doesn't handle negative values"
import math
power = math.ceil(math.log(a,2))
return math.pow(2,power)

def roundup_pow2i(a):
if type(a)!=type(0): raise RuntimeError, "Only works for ints!"
if a <=0: raise RuntimeError, "Oops, doesn't handle negative values"

next_one_up=1
while(next_one_up < a):
next_one_up = next_one_up << 1
return next_one_up

assert(roundup_pow2f(1)==1) # nearest power 1 = 2^0
assert(roundup_pow2f(2)==2)
assert(roundup_pow2f(3)==4)
assert(roundup_pow2f(4)==4)
assert(roundup_pow2f(5)==8)
assert(roundup_pow2f(7.9)==8)

assert(roundup_pow2i(1)==1)
assert(roundup_pow2i(2)==2)
assert(roundup_pow2i(3)==4)
assert(roundup_pow2i(4)==4)
assert(roundup_pow2i(5)==8)

There is some ambiguity about the exact needs of this somewhat anonymous Java programmer but in my world, when you say "round to the next" you usually mean "round to the nearest one up." So rounding up by 2's, if you input 2, the output is 2.

But I am not a Java programmer. Actually, this might be a trivial enough problem to try in Factor for learning purposes!

No comments: