# Taking the reverse power of a number

I have a question that I can’t seem to find any information on, and it’s making me wonder if it’s something I can do or not. What I want to do if figure out if a number is a power of two, and it would help significantly if I could even get a remainder towards the next one.

So as an example. I would like some type of functionality where I put in the number 8, and it tells me that it’s the third power of two, so it would return 3. This is the primary functionality I need.

As a bonus, it would be cool if I could know the number to the next highest square. IE I give it the number 12, the next highest power of two would be 16, so it returns the number 4, showing how much I need to make the number a clean power of 2

There is already a function for this. It’s called a logarithm. In Godot, there is only the natural log. If you took log base 2 of 8, it would return 3. Log base 2 of 12 is about 3.58. To get the base you want, take the natural log of x (8 in this case), and divide it by the natural log of your base (2 in this case), and that will get you what you want. Here is a function for it:

``````func based_log(base = 10, x = 10) - > float:
return (log(x) / log(base))
``````

This will give you what is shown in the first link. To get the next number, ceil it.

``````func next_log(base, x) -> int:
var first = based_log(base, x)
return ceil(first)
#Or, if you wanted the next power, use this instead:
#return base ** ceil(first)
``````

This should work, but I haven’t tried it.

1 Like

Ah yes of course, I complete forgot logarithms were a thing, thank you!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.