Sponsored
Sponsored
This approach involves successively dividing the number n
by 4 to check if it results in 1. If n
is a power of four, repeatedly dividing it by 4 should eventually reduce it to 1 with no remainder.
Time Complexity: O(log4 n) due to repeated division.
Space Complexity: O(1) because no additional space is used.
1function isPowerOfFour(n) {
2 if (n <= 0) return false;
3 while (n % 4 === 0) {
4 n /= 4;
5 }
6 return n === 1;
7}
This JavaScript function performs the iterative check using a loop, dividing n
by 4 until it either becomes 1 or a non-divisible value.
This approach harnesses logarithms to determine if a number is a power of four. For a number n
to be a power of four, the logarithm base 4 of n
should be an integer. Utilizing the change of base formula, this can be checked without directly using base 4 logarithm functions.
Time Complexity: O(1) as logarithmic operations are constant time.
Space Complexity: O(1).
1using System;
public class Solution {
public bool IsPowerOfFour(int n) {
if (n <= 0) return false;
double log_val = Math.Log10(n) / Math.Log10(4);
return Math.Floor(log_val) == log_val;
}
}
This C# code checks if n
is a power of four using logarithms, ensuring the computed value is a whole number.