Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Checking if a number is a valid power of 4 in JavaScript
We are required to write a JavaScript function that takes in a single integer, num, as the only argument. Our function should check whether this number is a valid power of 4 or not. If it is a power of 4, we should return true, false otherwise.
For example, if the input to the function is:
const num1 = 2356; const num2 = 16;
Then the output should be:
const output1 = false; const output2 = true;
Understanding Powers of 4
Powers of 4 are numbers that can be expressed as 4n where n is a non-negative integer:
- 40 = 1
- 41 = 4
- 42 = 16
- 43 = 64
- 44 = 256
Method 1: Using Loop with Math.pow()
This approach iterates through possible powers of 4 and checks for a match:
const num1 = 2356;
const num2 = 16;
const isPowerOfFour = (num = 1) => {
if (num num) {
break; // Optimization: stop if we exceed the number
}
}
return false;
};
console.log(isPowerOfFour(num1));
console.log(isPowerOfFour(num2));
false true
Method 2: Using Logarithms
A more mathematical approach using logarithms to check if log?(num) is a whole number:
const isPowerOfFourLog = (num) => {
if (num
true
true
true
true
false
Method 3: Using Division
Keep dividing by 4 until we can't divide evenly anymore:
const isPowerOfFourDivision = (num) => {
if (num
true
false
Comparison
| Method | Time Complexity | Readability | Notes |
|---|---|---|---|
| Loop with Math.pow() | O(log n) | High | Easy to understand, limited range |
| Logarithms | O(1) | Medium | Fastest, may have floating-point precision issues |
| Division | O(log n) | High | Simple logic, works for any size |
Complete Example
// Test all methods with various inputs
const testNumbers = [1, 4, 8, 16, 64, 100, 256, 1024];
testNumbers.forEach(num => {
console.log(`${num}: ${isPowerOfFourDivision(num)}`);
});
1: true 4: true 8: false 16: true 64: true 100: false 256: true 1024: true
Conclusion
The division method is generally the most reliable approach for checking powers of 4, as it avoids floating-point precision issues and works efficiently for numbers of any size. The logarithmic method is fastest but may have precision limitations with very large numbers.
