|
-
Jul 20th, 2005, 06:48 AM
#1
Thread Starter
Fanatic Member
How many divisions?
How can i establish how many times i need to divide a number by 2 before it gets to 0 without actually doing the divisions (these will be done later)?
I want to do this because i need to establish how many array spaces i need for all the divided numbers to go into.
For Example. If the number was 96, i would need to divide this 7 times before it goes to zero.
96
48
24
12
6
3
1.5
0
Last edited by x-ice; Jul 21st, 2005 at 09:26 AM.
-
Jul 20th, 2005, 08:41 AM
#2
Addicted Member
Re: How many divisions?
Let X be your number to be divided by 2 and n the number of times X can be divided by 2 before the result becomes less than 1. Then, X/2^n < 1. From this expression you derive n = log(X)/log(2) and approximate the result to the nearest upper integer. For instance:
X = 96; n = 7
X = 300; n = 9
X = 5000; n = 13
Hope this helps.
Last edited by Rassis; Jul 20th, 2005 at 08:48 AM.
...este projecto dos Deuses que os homens teimam em arruinar...
-
Jul 20th, 2005, 07:06 PM
#3
Thread Starter
Fanatic Member
Re: How many divisions?
 Originally Posted by Rassis
Let X be your number to be divided by 2 and n the number of times X can be divided by 2 before the result becomes less than 1. Then, X/2^n < 1. From this expression you derive n = log(X)/log(2) and approximate the result to the nearest upper integer. For instance:
X = 96; n = 7
X = 300; n = 9
X = 5000; n = 13
Hope this helps.
Ok i have a slight problem, the result in getting rounded down to the nearest integer in most cases (i guess it because it is below n.5). How can i prevent this from happening? Here is my code.
VB Code:
Private Function Dec2Bin(ByVal DecNum As Int32) As Int32
Dim DivNum As Int32
'Establish how many divisions will be done
DivNum = CInt(Log(DecNum) / (Log(2))[b] + 1[/b])
'TEST
MessageBox.Show(CStr(DivNum))
End Function
p.s. I have tried to add the code in bold, this solves the problem for the numbers that produce incorrect results (e.g 300 and 5000) but for the numbers that produce correct results (e.g. 96) it makes the result incorrect.
-
Jul 21st, 2005, 09:41 AM
#4
Addicted Member
Re: How many divisions?
I said that the result should be rounded up to the nearest integer and not rounded down. Thus you allways get the right number.
...este projecto dos Deuses que os homens teimam em arruinar...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|