8 posts
• Page **1** of **1**

I am trying to work out if a variable is in the power of 2 series (e.g. 2, 4, 8, 16, 32 etc). To do this I thought it would be best to take the log of the variable to base 2, if that number was an integer then the variable is within the series. However, I can't find a way to test if the number is an integer or a float/double. Is it possible to test this? If not is there another way to test if the variable is in the sequence?

Nothing goes unanswered!

**Posts:**434**Reputation:**3,446

B

24
S

5
G

1
As I'm not a math wiz I usually like to work with predefined lists for stuff like this (I assume there is a better way than what I'm going to suggest but it will probably work). Why not create a dictionary and load the possible variables (2,4,8 etc..) on start of layout and then at runtime when checking just iterate over the list until to see if the number you have matches any in the list. If match return true. depending on how large a number you expect to get you could init the list with a while loop to generate a very large of possible numbers

**Posts:**221**Reputation:**2,077

B

20
S

7
G

1
@briggybros Use the modulus operator. (%)

You can thest if a number is in the power of two like this numberToCheck % 2 = 0

The modulus operator is used to get the remainder of the division. So if you do 4/2 you will get 0 as the remainder so that's how you can check if is in the power of 2, if you try with 3/2 you will get 1 as remainder so it wont pass the check.

Hope that helps, I know my english is not that good.

You can thest if a number is in the power of two like this numberToCheck % 2 = 0

The modulus operator is used to get the remainder of the division. So if you do 4/2 you will get 0 as the remainder so that's how you can check if is in the power of 2, if you try with 3/2 you will get 1 as remainder so it wont pass the check.

Hope that helps, I know my english is not that good.

You do not have the required permissions to view the files attached to this post.

Last edited by donelwero on Tue Jun 03, 2014 4:39 pm, edited 1 time in total.

**Posts:**53**Reputation:**3,335

B

21
S

5
G

3
**Posts:**434**Reputation:**3,446

B

24
S

5
G

1
**Posts:**434**Reputation:**3,446

B

24
S

5
G

1
briggybros wrote:This is the solution for anyone else interested

Just as a matter of precision for someone who is not a math guru:

log(x)/log(2) = log_based_2(x) (log being a log based on any positive number)

so of course log(x)%log(2) ---> If 0, then the log based 2 of x is an integer, and so x is a power of 2

I'm not sure of the actual precision of the value of log(2) is stored, so keep that in mind too

Game design is all about decomposing the core of your game so it becomes simple instructions.

**Posts:**2,122**Reputation:**17,123

B

53
S

22
G

18
8 posts
• Page **1** of **1**

## Who is online |

Users browsing this forum: ChoosyZerk, lukewasthefish and 15 guests |