views:

141

answers:

4

Consider the equation below:

2 ** n = A

Let us assume A=64.

What is the easiest way to find the value of n?

I am currently using following two approaches

A= 64; n = 1; n+=1 while (A >> n) > 0; n-1

A= 64; n = 0; n+=1 until (A == ( 2 ** n));n

Is there a better approach?

Other way of stating the same problem:

2 = nth root A If I know the value of A, how do I determine the value of n?

+3  A: 

log2n = ln n / ln 2

hence

log_2_64 = Math.log(64) / Math.log(2)
stereofrog
+9  A: 

Try this:

def exp_value(n)
  Math.log(n) / Math.log(2)
end
JRL
Stuff like this makes me wish that I comprehended logarithms well, know of any good/simple online references?
The Wicked Flea
This is not complex mathematics - they teach this in high school: http://en.wikipedia.org/wiki/Logarithm
duffymo
@Duffymo: fair enough but (1) complex (or not) is a relative term here and (2) not all of us paid attention during high school math classes. There's no sense in telling someone, "this is trivial," if he or she asks for references to more information.
Telemachus
+4  A: 

Neither of the above answers is better than your first approach:

A= 64; n = 1; n+=1 while (A >> n) > 0; n-1

Evaluating Math.log(x) takes a lot longer than doing a dozen bit-shifts, and will also give you an answer like 5.99999999999980235 to make sense of.

See this SO question for some better ideas.

mobrule
+1  A: 

If you care about the problems mentioned by mobrule. How about this? It is the same as your own method but use built-in function to communicate the idea explictly.

    def exp_value a 
       (1..a).to_a.detect {|n| 2**n >=a}
    end

    exp_value 64
    => 6
pierr