The Power of a Number
One of the things we learn in algebra is exponents, that is the number 2 raised to the power of 4 is 16; 2 to the power of 0 is 1.
2^4 = 16, 2^0 = 1
The opposite of raising the power is finding the root of the number. Dividing 16 by 2 four times will get us 1. I will detail this below for solving the algorithm here. So when we divide 16 by 2, we simply do
16 / 2 = (2^4) / 2 = 2^(4 - 1) = 8
and we can keep doing this until we get 1,
2 / 2 = 2^(1 - 1) = 1.
I found this problem on Leet Code and it asks:
Given an integer n, return true if it is a power of three. Otherwise, return false.An integer n is a power of three, if there exists an integer x such that n == 3^x.
For this problem, I will solve a general case for any number.
Before I show how to solve it, exponents are useful in real life because if there are really massive numbers, we can save ourselves the time by writing exponents. I am sure you don’t want to write down a 1 with twenty-six zero’s after it.
10^26
We can see it is much easier to do and saves time too. It also makes doing math easier. Work smarter, not harder as a lot say.
Now we can focus on how to solve the problem. The first thing we know is that 1 is the zeroth power of any number so we want any number less than 1 to be automatically false. The code is merely
if(num < 1){
return false
}.
The next part is to divide the number “num” by another number I call “div”. As long as the remainder is zero, we keep dividing num by div until the remainder is no longer zero or hits 1. If it hits 1, we return true; if not, we return false. The code is
while(num % div === 0){
num /= div
}
if(num === 1){
return true
}
return false.
We use a while loop because we are using an arbitrary number, so we don’t want any constraints. The full code is
function power(num, div){
if(num < 1){
return false
}
while(num % div === 0){
num /= div
}
if(num === 1){
return true
}
return false
}.
Now we should test it. 16 is a power of 2 so we get true; if I use the number 44, we receive false. This can work for another number so let’s use 5. If I were to use
power(125, 5),
I receive true; when I use
power(120, 5),
the answer is false. We can see that the code indeed works. If there is a better way to solve it, let me know.