Sponsored
Sponsored
This approach leverages the fact that if a number n
is a power of three, it should be divisible by 3 repeatedly until it becomes 1. If at any step, n
is not divisible by 3 and it's greater than 1, it cannot be a power of three.
Time Complexity: O(log n)
Space Complexity: O(1)
1#include <stdbool.h>
2
3bool isPowerOfThree(int n) {
4 if (n < 1) return false;
5 while (n % 3 == 0) {
6 n /= 3;
7 }
8 return n == 1;
9}
The function checks divisibility by 3 in a loop, dividing n
repeatedly by 3 until it is either 1 (return true) or it isn't divisible by 3 anymore (return false).
This approach uses logarithms to determine if a number is a power of three. By taking the logarithm of the number and comparing it to the logarithm base 3, we can check if they form an integer ratio.
Time Complexity: O(1)
Space Complexity: O(1)
1public class
This Java method uses Math.log10()
to compute the logarithmic check for powers of three, ensuring precision.