Featured post
java - Calculate the number of times to divide by two -
greetings.
i have java method consider expensive, , i'm trying replace calls mathematical expression. problem is, suck @ math. mean really suck.
the following should explain pattern i'm trying exploit.
f(x) -> y f(x*2) -> f(x)+1
that is, whenever double value x, value y 1 greater x/2. here example output:
f(5) -> 6 f(10) -> 7 f(20) -> 8 f(40) -> 9 f(80) -> 10 f(160) -> 11 f(320) -> 12
my current approach brute force. i'm looping on x , test how many times can halve before reach 5, , add 6. works , faster call original method. looking more "elegant" or potentially cheaper solution.
accepted answer goes 1 manages me without pointing out how stupid :)
(the title sucks, because don't know i'm looking for)
have considered looking @ divide five, find power of 2 have, , add 6 power?
the general approach "given y find out power of x is" use logarithms. calculator try dividing log of 64 log of 2 , see 6.
so - divide five, take log, divide log of two, , add six.
- Get link
- X
- Other Apps
Comments
Post a Comment