1. Repeated Division by 4
Intuition
If n <= 0, return false. While n % 4 == 0, divide n /= 4. Return n == 1.
When to apply: Basic definition.
Algorithm
- Step 1: If n <= 0, return false.
- Step 2: While n % 4 == 0, n /= 4.
- Step 3: Return n == 1.
#include <iostream> using namespace std; bool isPowerOfFourBrute(int n) { if (n <= 0) return false; while (n % 4 == 0) { n /= 4; } return n == 1;} int main() { cout << boolalpha; cout << "Brute (16): " << isPowerOfFourBrute(16) << endl; // true cout << "Brute (8): " << isPowerOfFourBrute(8) << endl; // false cout << "Brute (1): " << isPowerOfFourBrute(1) << endl; // true return 0;}Time & Space Complexity
- Time complexity:
O(log4 n) - Space complexity:
O(1)